Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Classes\Steam;
- use App\Jobs\DepositConfirm;
- use App\Models\Item;
- use App\Models\Round;
- use App\Models\RoundDeposits;
- use App\Models\Trade;
- use App\Models\TradeLog;
- use App\Models\User;
- use Crypt_RSA;
- use DateTime;
- use Illuminate\Support\Facades\Cache;
- use Illuminate\Support\Facades\File;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Facades\Queue;
- use Math_BigInteger;
- class SteamBot extends SteamBase
- {
- public function __construct(array $data)
- {
- parent::__construct($data);
- if (!is_null($this->login)) {
- $auth = $this->steamAuth();
- $this->auth = $auth;
- $this->session_id = $auth['session_id'];
- $this->account_steamid = $auth['steamid'];
- $this->account_tradelink = $auth['tradelink'];
- $this->account_name = $auth['account_name'];
- $this->custom_acc_url = $auth['account_custom_name'];
- }
- }
- private function steamAuth($emailauth = false)
- {
- $cache_name = 'steam_bot_'.$this->bot_id;
- if (!Cache::has($cache_name)) {
- $rsa = json_decode(
- $this->openPage(
- $this->get_rsa_url,
- ['postdata' => ['username' => $this->login, 'donotcache' => time()]]
- )
- );
- if (isset($rsa->success)) {
- if (!$rsa->success) {
- return ['error' => 'Error while retrieving RSA key'];
- }
- $password = $this->encryptPassword(
- $this->password,
- ['mod' => $rsa->publickey_mod, 'exp' => $rsa->publickey_exp]
- );
- $params = [
- 'password' => $password,
- 'username' => $this->login,
- 'twofactorcode' => '',
- 'loginfriendlyname' => '',
- 'rsatimestamp' => $rsa->timestamp,
- 'remember_login' => 'true',
- 'captchagid' => -1,
- 'captcha_text' => '',
- 'donotcache' => time(),
- 'emailauth' => @$emailauth['code'],
- 'emailsteamid' => @$emailauth['emailsteamid']
- ];
- $login = json_decode($this->openPage($this->login_url, ['postdata' => $params]), true);
- if ($login['success']) {
- $params = $login['transfer_parameters'];
- $params['remember_login'] = 'true';
- $cookie = $this->openPage($login['transfer_url'], ['postdata' => $params]);
- $offer_page = $this->openPage("http://steamcommunity.com/id/me/tradeoffers/privacy");
- $pattern = '/\<input size="45" type="text" class="trade_offer_access_url" id="trade_offer_access_url" value="(.*?)" readonly\>/';
- preg_match($pattern, $offer_page, $trade);
- preg_match('/sessionid ([a-z0-9]{24})/', file_get_contents($this->bot_cookie_file), $session_id);
- preg_match(
- '/<span class="profile_small_header_name"><a class="whiteLink" href="(.+?)">(.+?)<\/a><\/span>/',
- $offer_page,
- $name
- );
- //var_dump($name);
- if (isset($name[1], $name[2], $params['steamid'], $trade[1], $session_id[1])) {
- $return = [
- 'account_custom_name' => $name[1],
- 'account_name' => $name[2],
- 'steamid' => $params['steamid'],
- 'session_id' => @$session_id[1],
- 'tradelink' => $trade[1]
- ];
- Cache::put($cache_name, $return, 15);
- return $return;
- }
- }
- }
- return false;
- } else {
- return Cache::get($cache_name);
- }
- }
- public function openPage($url, $flags = null)
- {
- if (is_null($flags)) {
- $flags = false;
- }
- $flags['ref'] = (isset($flags['ref']) ? $flags['ref'] : $this->default_ref);
- $flags = [
- 'postdata' => @$flags['postdata'],
- 'ref' => @$flags['ref'],
- 'return_headers' => @$flags['return_headers'],
- 'return_only_cookies' => @$flags['return_only_cookies'],
- 'timeout' => @$flags['timeout']
- ];
- $s = curl_init();
- curl_setopt($s, CURLOPT_FOLLOWLOCATION, true);
- curl_setopt($s, CURLOPT_URL, $url);
- curl_setopt($s, CURLOPT_COOKIEJAR, $this->bot_cookie_file);
- curl_setopt($s, CURLOPT_COOKIEFILE, $this->bot_cookie_file);
- curl_setopt($s, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($s, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($s, CURLOPT_SSL_VERIFYHOST, false);
- curl_setopt($s, CURLOPT_HEADER, $flags['return_headers'] || $flags['return_only_cookies']);
- curl_setopt($s, CURLOPT_USERAGENT, $this->default_useragent);
- if ($flags['timeout']) {
- curl_setopt($s, CURLOPT_CONNECTTIMEOUT, $flags['timeout']);
- }
- if ($flags['postdata']) {
- curl_setopt($s, CURLOPT_POST, true);
- curl_setopt($s, CURLOPT_POSTFIELDS, http_build_query($flags['postdata']));
- }
- if ($flags['ref']) {
- curl_setopt($s, CURLOPT_REFERER, $flags['ref']);
- }
- $cookie = $this->cookie;
- $cookie .= $this->additional_cookie;
- curl_setopt($s, CURLOPT_COOKIE, $cookie);
- $res = curl_exec($s);
- curl_close($s);
- if ($flags['return_only_cookies']) {
- $res = $this->parseCookie($res, true);
- }
- return $res;
- }
- private function parseCookie($string, $into_array = false)
- {
- preg_match_all("/Set-Cookie: (.*?)=(.*?);/i", $string, $res);
- $cookie = null;
- if (count($res) > 0) {
- foreach ($res[1] as $key => $value) {
- if (!$into_array) {
- $cookie .= $value.'='.$res[2][$key].'; ';
- if (strstr($value, 'steamMachineAuth')) {
- file_put_contents($this->bot_cookie_file, $value.'='.$res[2][$key].';');
- }
- } else {
- $cookie[$value] = $res[2][$key];
- }
- }
- }
- return $cookie;
- }
- private function encryptPassword($password, $keys)
- {
- if ($password && is_array($keys)) {
- $RSA = new Crypt_RSA();
- $RSA->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
- $n = new math_biginteger($keys['mod'], 16);
- $e = new math_biginteger($keys['exp'], 16);
- $key = ['modulus' => $n, 'publicExponent' => $e];
- $RSA->loadKey($key, CRYPT_RSA_PUBLIC_FORMAT_RAW);
- return base64_encode($RSA->encrypt($password, false));
- }
- return false;
- }
- public function botReload()
- {
- for ($i = 1; $i < 5; $i++) {
- @unlink($this->bot_cookie_file);
- $auth = $this->steamAuth();
- echo 'New session id: '.$auth['session_id'].PHP_EOL;
- if (isset($auth['session_id'], $auth['steamid'], $auth['tradelink'])) {
- break;
- }
- }
- return $i;
- }
- public function updateBotInventory($bot_id)
- {
- $inventory = json_decode(
- $this->openPage(
- sprintf($this->get_inventory, $this->account_steamid, $this->app_id),
- ['timeout' => 1]
- )
- );
- Cache::forget("bot_inventory_{$bot_id}");
- if ($inventory) {
- $inventory = $inventory->rgInventory;
- $bot_inventory = collect();
- foreach ($inventory as $asset_id => $val) {
- $bot_inventory->push(['asset_id' => $asset_id, 'class_id' => $val->classid, 'reserved' => false]);
- }
- $bot_inventory = $this->updateBotInventoryInformation($bot_inventory);
- Cache::forever("bot_inventory_{$bot_id}", $bot_inventory);
- }
- }
- public function updateBotInventoryInformation($inventory)
- {
- $trades = Trade::getSending();
- $reserved_items = [];
- $bot_inventory = collect($inventory);
- foreach ($trades as $trade) {
- $items = collect(json_decode($trade->items));
- $status = $this->getTradeOffer($trade->trade_id)['response']['offer']['trade_offer_state'];
- if($status == 3) {
- Trade::setDone($trade->trade_id);
- }
- foreach ($items as $item) {
- $reserved_items[] = $item->asset_id;
- }
- }
- foreach ($reserved_items as $asset_id) {
- $bot_inventory->transform(
- function ($item) use ($asset_id) {
- if ($item['asset_id'] == $asset_id) {
- $item['reserved'] = true;
- }
- return $item;
- }
- );
- }
- return $bot_inventory;
- }
- public function getAccountInventory(
- $steam_id,
- $cache = false,
- $sort_by_price = false,
- $nocache = false,
- $display_info = true,
- $lang = false
- ) {
- $cached_inventory = storage_path('/framework/inventories/').$steam_id.'.json';
- if (time() - @filemtime($cached_inventory) > $this->inventory_cache_time || $nocache) {
- $json_inventory = $this->openPage(
- sprintf($this->get_inventory, $steam_id, $this->app_id),
- ['timeout' => 1]
- );
- } else {
- return json_decode(file_get_contents($cached_inventory), true, JSON_UNESCAPED_UNICODE);
- }
- $inventory = json_decode($json_inventory, true, JSON_UNESCAPED_UNICODE);
- $items = [];
- $info = ['total_price' => 0, 'total_items' => 0];
- if (isset($inventory['rgInventory'])) {
- foreach ($inventory['rgInventory'] as $asset_id => $val) {
- $desc = $inventory['rgDescriptions']["{$val['classid']}_{$val['instanceid']}"];
- $key = $val['classid'];
- if (isset($items['items'][$key])) {
- $items['items'][$key]['count']++;
- $items['items'][$key]['asset_id'][] = (string)$asset_id;
- } else {
- if ($cache == true) {
- $item_info = Item::find($val['classid']);
- if (!empty($item_info)) {
- $item_info = $item_info->toArray();
- } else {
- $item_info = $this->itemGetInfo($val['classid'], true, true);
- }
- if (!$lang) {
- if (isset($item_info['en_name'])) {
- $name = $item_info['en_name'];
- } else {
- $name = null;
- }
- } else {
- if (isset($item_info[$lang.'_name'])) {
- $name = $item_info[$lang.'_name'];
- } else {
- if (isset($item_info['en_name'])) {
- $name = $item_info['en_name'];
- } else {
- $name = null;
- }
- }
- }
- } else {
- $item_info = $this->itemGetInfo($val['classid']);
- $name = $item_info['name'];
- }
- $items['items'][$key] = [
- 'asset_id' => [(string)$asset_id],
- 'classid' => $key,
- 'count' => 1,
- 'item_name' => $name,
- 'item_price' => $item_info['price'],
- 'rarity' => $item_info['rarity'],
- 'quality' => $item_info['quality'],
- ];
- }
- $info['total_price'] += $items['items'][$key]['item_price'];
- $info['total_items']++;
- }
- if ($display_info) {
- $items['info'] = $info;
- }
- }
- if ($sort_by_price) {
- if (isset($items['items'])) {
- $items['items'] = collect($items['items'])->sortByDesc('item_price')->toArray();
- } else {
- $items['items'] = [];
- }
- $sortedItems = [];
- $number = 0;
- foreach ($items['items'] as $key => $item) {
- $number++;
- $sortedItems[$number] = $item;
- }
- unset($items['items']);
- $items['items'] = $sortedItems;
- }
- if (!$nocache) {
- File::put($cached_inventory, json_encode($items), JSON_UNESCAPED_UNICODE);
- }
- return $items;
- }
- public function itemGetInfo($class_id, $updateData = false, $updatePrice = false, $lang = false)
- {
- $array = [];
- $item = Item::getInfo($class_id);
- if ((empty($item)) OR (empty($item->ru_name)) OR (empty($item->en_name)) OR ($updateData)) {
- $result = json_decode(
- mb_convert_encoding(
- $this->openPage(
- sprintf($this->item_info_by_class, $this->app_id, $this->api_key, $class_id),
- ['timeout' => 3]
- ),
- "UTF-8",
- "auto"
- ),
- true,
- JSON_UNESCAPED_UNICODE
- );
- $condition = !preg_match('/Сувенирный/', @$result['result'][$class_id]['market_name']) || preg_match(
- '/Сувенирный набор/',
- @$result['result'][$class_id]['market_name']
- );
- if (isset($result['result'][$class_id]['market_hash_name']) && $condition) {
- $en_name = $result['result'][$class_id]['market_hash_name'];
- $ru_name = $result['result'][$class_id]['market_name'];
- preg_match('/\((.*?)\)/', $ru_name, $exterior);
- $quality = explode(',', $result['result'][$class_id]['type']);
- if (strpos($result['result'][$class_id]['type'], 'Нож') !== false) {
- $quality[] = 'Нож';
- }
- $exterior = (isset($exterior[1]) ? $exterior[1] : '');
- $quality = (is_array($quality) ? end($quality) : '');
- $array = [
- 'id' => $class_id,
- 'ru_name' => $ru_name,
- 'en_name' => $en_name,
- 'rarity' => $this->defineRarity($quality),
- 'quality' => $this->defineQuality($exterior),
- 'last_update_time' => $this->date
- ];
- if (empty($item)) {
- Item::addItem($array);
- } else {
- unset($array['id']);
- Item::updateItem($class_id, $array);
- }
- }
- } else {
- $array = $item->toArray();
- }
- if (isset($array['last_update_time'])) {
- $date = new DateTime($array['last_update_time']);
- $updateTime = time() > $date->modify("+{$this->item_cache_time} minutes")->getTimestamp();
- } else {
- $updateTime = true;
- }
- if (((!isset($array['price'])) OR ($updateTime) OR ($updatePrice)) AND !empty($array)) {
- $res = json_decode(
- $this->openPage(
- sprintf($this->get_item_price, $this->currency, $this->app_id, urlencode($array['en_name'])),
- ['timeout' => 2]
- )
- );
- if (isset($res->success)) {
- $price = null;
- if (isset($res->lowest_price)) {
- $price = $res->lowest_price;
- } elseif (isset($res->median_price)) {
- $price = $res->median_price;
- }
- switch ($this->currency) {
- case 5:
- $price = floatval(str_replace([',', ' руб.'], ['.', null], $price));
- break;
- default:
- $price = floatval(str_replace('$', null, $price));
- }
- $array['price'] = $price;
- Item::updatePrice($class_id, $price);
- }
- }
- if (@$array['price'] && @$array['en_name']) {
- if (!$lang) {
- $name = $array['en_name'];
- } else {
- $name = $array["{$lang}_name"];
- }
- return [
- 'price' => $array['price'],
- //'ru_name' => $array['ru_name'],
- 'name' => $name,
- 'rarity' => $array['rarity'],
- 'quality' => $array['quality']
- ];
- }
- return false;
- }
- public function defineQuality($quality)
- {
- $quality = trim(mb_strtolower($quality));
- switch ($quality) {
- case 'немного поношенное':
- $return = 'mw';
- break;
- case 'прямо с завода':
- $return = 'fn';
- break;
- case 'после полевых испытаний':
- $return = 'ft';
- break;
- case 'поношенное':
- $return = 'ww';
- break;
- case 'закаленное в боях':
- $return = 'bs';
- break;
- default:
- $return = '';
- }
- return $return;
- }
- public function defineRarity($rarity)
- {
- $rarity = trim(mb_strtolower($rarity));
- switch ($rarity) {
- case 'нож':
- case 'контрабандное':
- $return = 'knife';
- break;
- case 'базового класса':
- case 'ширпотреб':
- $return = 'consumer';
- break;
- case 'промышленное качество':
- $return = 'uncommon';
- break;
- case 'армейское качество':
- case 'высшего класса':
- $return = 'mil-spec';
- break;
- case 'тайное':
- $return = 'restricted';
- break;
- case 'засекреченное':
- case 'экзотичного вида':
- $return = 'covert';
- break;
- case 'запрещенное':
- case 'примечательного типа':
- $return = 'exceedingly-rare';
- break;
- default:
- $return = 'consumer';
- }
- return $return;
- }
- public function getItemsValue($steam_id, $no_cache = false)
- {
- $cache = "inventory_{$steam_id}";
- $result = false;
- if (!Cache::has($cache) || $no_cache) {
- $attempts = 0;
- foreach ($this->itemValueServer as $server) {
- $url = "http://{$server}.appspot.com/ParseInv?id={$steam_id}&app={$this->app_id}";
- $file_headers = @get_headers($url);
- if (strtolower($file_headers[0]) === strtolower('HTTP/1.0 200 Ok')) {
- $json_inventory = file_get_contents($url);
- $result = collect(json_decode($json_inventory))->sortBy('price', JSON_UNESCAPED_UNICODE);
- if (($result['success'] !== false) OR ($attempts > count($this->itemValueServer))) {
- Cache::put($cache, $json_inventory, $this->inventory_cache_time);
- break;
- } else {
- $result = ['error' => trans('notify.steam_unavailable')];
- }
- }
- $attempts++;
- }
- } else {
- $result = collect(json_decode(Cache::get($cache), JSON_UNESCAPED_UNICODE))->sortBy('price');
- }
- return $result;
- }
- public function sortItemsByPrice($price, $partner_id, $items_count, $trade_link, $comment, $start_items = 0)
- {
- $items = [];
- foreach ($this->getAccountInventory($this->account_steamid, $price, true) as $key => $value) {
- if (is_array(@$value['asset_id'])) {
- foreach ($value['asset_id'] as $asset_id) {
- $items[] = ['appid' => $this->app_id, 'contextid' => 2, 'amount' => 1, 'assetid' => $asset_id];
- }
- }
- }
- $items = array_slice($items, $start_items * $items_count, $items_count);
- return $this->tradeSend($partner_id, $comment, $trade_link, $items);
- }
- public function tradeSend($partner_id, $trade_offer_message, $trade_offer_link, $items)
- {
- $send_url = "https://steamcommunity.com/tradeoffer/new/send";
- preg_match(
- '/https:\/\/steamcommunity.com\/tradeoffer\/new\/\?partner=(.*)&token=(.*)/',
- $trade_offer_link,
- $token
- );
- $data = [
- 'sessionid' => $this->session_id,
- 'serverid' => 1,
- 'partner' => $partner_id,
- 'tradeoffermessage' => $trade_offer_message,
- 'json_tradeoffer' => $this->getItemsList($items),
- 'captcha' => '',
- 'trade_offer_create_params' => json_encode(['trade_offer_access_token' => $token[2]]),
- ];
- return json_decode(
- $this->openPage($send_url, ['postdata' => $data, 'ref' => $trade_offer_link], ['timeout' => 4])
- );
- }
- private function getItemsList($array)
- {
- $array = [
- 'newversion' => true,
- 'version' => 2,
- 'me' => ['assets' => $array, 'currency' => [], 'ready' => false],
- 'them' => ['assets' => [], 'currency' => [], 'ready' => false]
- ];
- return json_encode($array);
- }
- public function setDeposit()
- {
- return $this->trade_offer;
- }
- public function confirmTrade($trade_id)
- {
- $status = false;
- if (isset($trade_id)) {
- $deposit = RoundDeposits::findDeposit($trade_id);
- $sender_steam_id = (string)$deposit->user;
- $user_data = User::getInfo($sender_steam_id);
- $reason = trans('notify.steam_error', [], 'messages', $user_data->language);
- $deposit->items = json_decode($deposit->items);
- if ($user_data) {
- if (count($deposit->items) > 0) {
- if (!is_null(isset($user_data->trade_offer))) {
- if ($deposit->total_items <= config('roulette.steam_helper.max_item_count')
- && $deposit->total_sum >= config('roulette.steam_helper.min_bet')
- ) {
- RoundDeposits::setProgress($trade_id, true);
- Queue::push(new DepositConfirm($trade_id));
- $status = true;
- } else {
- $reason = trans('notify.wrong_conditions', [], 'messages', $user_data->language);
- }
- } else {
- $reason = trans('notify.set_trade_url', [], 'messages', $user_data->language);
- }
- }
- } else {
- $reason = trans('notify.user_404', [], 'messages', $user_data->language);
- }
- if (!$status) {
- $result = [
- 'result' => trans('notify.trade_not_confirmed', [], 'messages', $user_data->language),
- 'reason' => $reason,
- 'user' => $sender_steam_id,
- 'error' => true
- ];
- $this->sockets->notify($result);
- }
- }
- }
- public function tradeDeclineByUser($trade_id)
- {
- $deposit = RoundDeposits::findDeposit($trade_id);
- $return = json_decode($this->tradeDecline($trade_id));
- $user_data = User::getInfo($deposit->user);
- if (isset($return->strError)) {
- Log::info(['result' => 'Deposit error', 'steam_response' => "$return->strError"]);
- $this->sockets->notify(
- [
- 'result' => trans('notify.steam_lag', [], 'messages', $user_data->language),
- 'steam_response' => trans('notify.trade_lag', [], 'messages', $user_data->language),
- 'user' => $deposit->user,
- 'error' => true
- ]
- );
- return false;
- } else {
- $result = [
- 'message' => trans('notify.trade_declined', [], 'messages', $user_data->language),
- 'user' => $deposit->user
- ];
- $this->sockets->notify(
- [
- 'result' => 'trade_declined',
- 'user' => $deposit->user,
- 'trade_id' => $trade_id,
- 'hidden' => true,
- 'remove' => true
- ]
- );
- $this->sockets->notify($result);
- return true;
- }
- }
- public function getTradeOffer($trade_id)
- {
- // 1 - инвалид, 2 - гуд, 3 - обмен принят тем, кому был отправлен, 4 - контрпредложение, 5 - истек срок, 6 - отправщик отменил трейд, 7 - получатель отменил трейд, 8 - вещи больше не актуальны, 9 - подтверждение по мылу, 10 - получатель отменил
- $res = json_decode(
- $this->openPage(sprintf($this->get_trade_offer, $this->api_key, $trade_id), ['timeout' => 3]),
- true,
- JSON_UNESCAPED_UNICODE
- );
- return $res;
- }
- /**
- * @param bool|true $incoming
- * @return array|mixed
- */
- public function getTradesList($incoming = true)
- {
- $deposits_confirm = RoundDeposits::all();
- if (isset($deposits_confirm)) {
- foreach ($deposits_confirm as $deposit) {
- if (date('Y-m-d H:i:s') > $deposit->created_at) {
- $user_data = User::getInfo($deposit->user);
- RoundDeposits::find($deposit->trade_id)->delete();
- $this->tradeDecline($deposit->trade_id);
- $result = [
- 'result' => trans('notify.trade_declined', [], 'messages', $user_data->language),
- 'reason' => trans('notify.trade_expired', [], 'messages', $user_data->language),
- 'user' => $deposit->user,
- 'trade_id' => $deposit->trade_id,
- 'error' => true
- ];
- $this->sockets->notify($result);
- }
- }
- }
- // 1 - инвалид, 2 - гуд, 3 - обмен принят тем, кому был отправлен, 4 - контрпредложение, 5 - истек срок, 6 - отправщик отменил трейд, 7 - получатель отменил трейд, 8 - вещи больше не актуальны, 9 - подтверждение по мылу, 10 - получатель отменил
- $get_var = ($incoming ? 'get_received_offers=1' : 'get_sent_offers=1');
- $result_key = ($incoming ? 'trade_offers_received' : 'trade_offers_sent');
- $res = json_decode(
- $this->openPage(sprintf($this->get_trades_list, $this->api_key, $get_var, time()), ['timeout' => 3]),
- true,
- JSON_UNESCAPED_UNICODE
- );
- if (count($res['response']) > 0) {
- $res = $res['response'][$result_key];
- foreach ($res as $key => $value) {
- if ($res[$key]['trade_offer_state'] == 2) {
- $res[$key]['items'] = [];
- $res[$key]['total_items'] = 0;
- $res[$key]['total_sum'] = 0;
- $res[$key]['items_without_price'] = 0;
- $error = false;
- $reason = null;
- $user = (string)$this->convertSteamId($res[$key]['accountid_other']);
- $user_data = User::getInfo($user);
- if (isset($res[$key]['items_to_receive'])) {
- foreach ($res[$key]['items_to_receive'] as $item) {
- if ($item['appid'] == $this->app_id) {
- $info = $this->itemGetInfo($item['classid']);
- if (!$info) {
- $res[$key]['items_without_price']++;
- $error = true;
- $reason = trans('notify.no_price_item', [], 'messages', $user_data->language);
- } else {
- $res[$key]['total_items']++;
- $res[$key]['total_sum'] += $info['price'];
- $res[$key]['items'][] = [
- 'price' => $info['price'],
- 'assetid' => (string)$item['assetid'],
- 'classid' => (string)$item['classid']
- ];
- }
- } else {
- $reason = trans('notify.wrong_appid', [], 'messages', $user_data->language);
- $error = true;
- }
- }
- if ($res[$key]['total_items'] > config('roulette.steam_helper.max_item_count')) {
- $error = true;
- $reason = trans(
- 'notify.wrong_conditions.max_items',
- [
- 'max' => config('roulette.steam_helper.max_item_count'),
- 'current' => $res[$key]['total_items']
- ],
- 'messages',
- $user_data->language
- );
- }
- if ($res[$key]['total_sum'] < config('roulette.steam_helper.min_bet')) {
- $error = true;
- $reason = trans(
- 'notify.wrong_conditions.low_price',
- [
- 'min' => config('roulette.steam_helper.min_bet'),
- 'current' => $res[$key]['total_sum']
- ],
- 'messages',
- $user_data->language
- );
- }
- if (!$error) {
- $trade_id = $res[$key]['tradeofferid'];
- $tradeExist = RoundDeposits::find($trade_id);
- if (is_null($tradeExist)) {
- $user = (string)$this->convertSteamId($res[$key]['accountid_other']);
- $items = collect($res[$key]['items'])->sortByDesc('price')->toArray();
- $sortedItems = [];
- foreach ($items as $item) {
- $sortedItems[] = $item;
- }
- unset($res[$key]['items']);
- $res[$key]['items'] = $sortedItems;
- unset($items, $sortedItems);
- /*на серверах стима время идет по другому гейб чертов наркоман
- $date = new DateTime(date('Y-m-d H:i:s', $res[$key]['time_created']));*/
- $date = new DateTime(date('Y-m-d H:i:s'));
- $trade_decline_time = config('roulette.trade_decline_time');
- $created_at = date(
- 'Y-m-d H:i:s',
- $date->modify("+{$trade_decline_time} seconds")->getTimestamp()
- );
- RoundDeposits::create(
- [
- 'trade_id' => $trade_id,
- 'items' => json_encode($res[$key]['items']),
- 'total_items' => $res[$key]['total_items'],
- 'total_sum' => $res[$key]['total_sum'],
- 'user' => $user,
- 'bot_id' => $this->bot_id,
- 'created_at' => $created_at,
- ]
- );
- $result = [
- 'result' => 'trade_confirm',
- 'trade_id' => $trade_id,
- 'items' => json_encode($res[$key]['items']),
- 'user' => $user,
- 'hidden' => true
- ];
- $this->sockets->notify($result);
- unset($user, $result);
- }
- unset($trade_id);
- } else {
- $user = (string)$this->convertSteamId($res[$key]['accountid_other']);
- $this->tradeDecline($res[$key]['tradeofferid']);
- $result = [
- 'message' => trans(
- 'notify.trade_declined',
- [],
- 'messages',
- $user_data->language
- ),
- 'reason' => $reason,
- 'user' => $user,
- 'error' => true
- ];
- $this->sockets->notify($result);
- unset($res[$key]);
- }
- }
- unset($res[$key]['items_to_receive']);
- } else {
- $user = (string)$this->convertSteamId($res[$key]['accountid_other']);
- /*проверяем остался ли такой трейд в базе*/
- $trade_id = $res[$key]['tradeofferid'];
- $round_deposit = RoundDeposits::find($trade_id);
- if (isset($round_deposit)) {
- $this->tradeDecline($trade_id);
- $result = [
- 'user' => $user,
- 'trade_id' => $trade_id,
- 'error' => true,
- 'hidden' => true,
- 'remove' => true
- ];
- $this->sockets->notify($result);
- $round_deposit->delete();
- }
- unset($res[$key], $user);
- }
- }
- return $res;
- }
- return [];
- }
- public function tradeDecline($tradeOfferId)
- {
- $data = ['tradeofferid' => $tradeOfferId];
- $decline_url = "https://api.steampowered.com/IEconService/DeclineTradeOffer/v1/?key={$this->api_key}";
- return $this->openPage($decline_url, ['postdata' => $data, 'timeout' => 3]);
- }
- public function convertSteamId($steam_id)
- {
- return bcadd($steam_id, "76561197960265728");
- }
- public function tradeAccept($partner, $tradeOfferId)
- {
- $accept_url = "https://steamcommunity.com/tradeoffer/{$tradeOfferId}/accept";
- $ref = "https://steamcommunity.com/tradeoffer/{$tradeOfferId}/";
- $data = [
- 'sessionid' => $this->session_id,
- 'tradeofferid' => $tradeOfferId,
- 'serverid' => 1,
- 'captcha' => '',
- 'partner' => $partner
- ];
- $result = $this->openPage($accept_url, ['postdata' => $data, 'ref' => $ref, 'timeout' => 3]);
- return $result;
- }
- public function tradeCancel($tradeOfferId)
- {
- $cancel_trade = "https://steamcommunity.com/tradeoffer/{$tradeOfferId}/cancel";
- $ref = "https://steamcommunity.com/tradeoffer/{$tradeOfferId}/";
- $data = ['sessionid' => $this->session_id];
- return $this->openPage($cancel_trade, ['postdata' => $data, 'ref' => $ref, 'timeout' => 3]);
- }
- public function userBlock($steamid)
- {
- $data = ['sessionID' => $this->session_id, 'steamid' => $steamid];
- return $this->openPage('http://steamcommunity.com/actions/BlockUserAjax', ['postdata' => $data]);
- }
- public function userUnblock($steamid)
- {
- $data = ['action' => 'unignore', 'friends['.$steamid.']' => 1];
- return $this->openPage(
- $this->custom_acc_url.'/friends/blocked/?success=unignore&c=1',
- ['postdata' => $data, 'ref' => $this->custom_acc_url.'/friends/blocked/?success=unignore&c=1']
- );
- }
- public function profileEdit($nickname, $summary, $custom_url = '')
- {
- $data = [
- 'personaName' => $nickname,
- 'sessionID' => $this->session_id,
- 'type' => 'profileSave',
- 'summary' => $summary,
- 'customURL' => $custom_url,
- 'primary_group_steamid' => 0,
- 'favorite_badge_badgeid' => '',
- 'weblink_1_title' => '',
- 'weblink_1_url' => '',
- 'weblink_2_title' => '',
- 'weblink_2_url' => '',
- 'weblink_3_title' => '',
- 'weblink_3_url' => '',
- 'real_name' => '',
- 'country' => '',
- 'state' => '',
- 'city' => '',
- 'profile_background' => '',
- 'favorite_badge_communityitemid' => ''
- ];
- $auth = $this->auth;
- $auth['account_name'] = $nickname;
- $auth['account_custom_name'] = ($custom_url ? 'http://steamcommunity.com/id/'.$custom_url : $auth['account_custom_name']);
- $this->cache->set('auth', $auth);
- return $this->openPage($this->custom_acc_url.'/edit', ['postdata' => $data]);
- }
- public function steamStatus()
- {
- $cache = "steam_status";
- if (!Cache::has($cache)) {
- $url = "https://crowbar.steamdb.info/Barney";
- $data = $this->openPage($url);
- $result = collect(json_decode($data))["services"]->csgo;
- Cache::put($cache, $data, 1);
- } else {
- $result = collect(json_decode(Cache::get($cache)))["services"]->csgo;
- }
- if (strtolower($result->title) == "webapi offline") {
- $this->sockets->send('steam_status', $result);
- }
- }
- public function checkTrades($errors = false)
- {
- if (!$errors) {
- $trades = Trade::where('status', 'new')->get();
- } else {
- $trades = Trade::where('status', 'error')->get();
- }
- $this->updateBotInventory($this->bot_id);
- $bot_inventory = collect(Cache::get("bot_inventory_{$this->bot_id}"));
- foreach ($trades as $key => $trade) {
- $reason = 'Trade not found';
- if (str_contains($trade['type'], 'reward')) {
- $round_id = json_decode($trade['type'])->reward;
- $round = Round::getInfo($round_id);
- $winner = User::getInfo($round->winner);
- foreach (json_decode($trade['items']) as $item) {
- $items[] = (array)$item;
- }
- if (!empty($items)) {
- $item_error = false;
- $reason_items = '';
- $items_commission = [];
- foreach ($items as $item) {
- if (!isset($item['commission'])) {
- $bot_item_asset = $bot_inventory->where('asset_id', "{$item['assetid']}")->where(
- 'reserved',
- false
- )->first();
- $bot_item = $bot_inventory->where('class_id', "{$item['classid']}")->where(
- 'reserved',
- false
- )->first();
- $item_info = Item::find($item['classid']);
- if (!is_null($bot_item_asset)) {
- $items_to_send[] = [
- 'appid' => $this->app_id,
- 'contextid' => '2',
- 'amount' => 1,
- 'assetid' => $bot_item_asset['asset_id']
- ];
- $bot_inventory->transform(
- function ($item) use ($bot_item_asset) {
- if ($item['asset_id'] == $bot_item_asset['asset_id']) {
- $item['reserved'] = true;
- }
- return $item;
- }
- );
- } elseif (is_null($bot_item_asset) && $bot_item) {
- $items_to_send[] = [
- 'appid' => $this->app_id,
- 'contextid' => '2',
- 'amount' => 1,
- 'assetid' => $bot_item['asset_id']
- ];
- $bot_inventory->transform(
- function ($item) use ($bot_item) {
- if ($item['asset_id'] == $bot_item['asset_id']) {
- $item['reserved'] = true;
- }
- return $item;
- }
- );
- } else {
- $reason_items .= " {$item_info->en_name}";
- $item_error = true;
- }
- } else {
- $items_commission[] = $item;
- }
- }
- if (!$item_error) {
- if (!empty($items_to_send)) {
- $trade_items = collect($items_to_send)->map(
- function ($item) use ($bot_inventory) {
- return [
- 'asset_id' => $item['assetid'],
- 'class_id' => $bot_inventory->where('asset_id', $item['assetid'])->first(
- )['class_id']
- ];
- }
- );
- $commission_items = collect($items_commission)->map(
- function ($item) use ($bot_inventory) {
- return [
- 'asset_id' => $item['assetid'],
- 'class_id' => $item['classid']
- ];
- }
- );
- $res = $this->tradeSend(
- $winner->id,
- trans('steam_message.win', ['round' => $round_id]),
- $winner->trade_offer,
- $items_to_send
- );
- if (isset($res->tradeofferid)) {
- Trade::where('id', $trade['id'])->update(
- [
- 'status' => 'sending',
- 'items' => $trade_items,
- 'commission' => $commission_items,
- 'trade_id' => $res->tradeofferid
- ]
- );
- Round::where('id', $round_id)->update(
- ['status' => 'done']
- );
- $result = ['result' => 'Trade sent', 'reason' => ''];
- } else {
- if (isset($res->strError)) {
- $reason = (string)$res->strError;
- }
- }
- } else {
- $reason = 'Cant find items in bot inventory';
- }
- } else {
- $reason = "Items cant be found:{$reason_items}";
- }
- } else {
- $reason = 'Cant load trade items';
- }
- if (!isset($result)) {
- $result = ['result' => 'Trade not sent', 'reason' => $reason, 'error' => true];
- Round::where('id', $round_id)->update(
- ['status' => 'error']
- );
- Trade::where('id', $trade['id'])->update(['status' => 'error']);
- $bot_inventory->transform(
- function ($botItem) {
- if(isset($items_to_send)) {
- foreach ($items_to_send as $item) {
- if ($botItem['asset_id'] == $item['asset_id']) {
- $botItem['reserved'] = false;
- }
- }
- }
- return $botItem;
- }
- );
- }
- }
- TradeLog::create(
- ['trade_id' => $trade['id'], 'result' => $result['result'], 'response' => $result['reason']]
- );
- unset($items);
- unset($items_to_send);
- unset($result);
- }
- }
- }
Add Comment
Please, Sign In to add comment