public function MakeRequest($endpoint, $data_string, $method, $retry_count = 0) { $log_msg = "Attempt #" . ($retry_count + 1) . "\r\n\r\n" . $data_string; $log_seq = 0; $func_args = func_get_args(); $func_log_id = DataLoadLogDAO::startFunction($this->db, $this->data_load_id, __CLASS__, __FUNCTION__, $func_args); if ($retry_count > 0) { echo "Retry Attempt #{$retry_count}\r\n"; } if ($retry_count >= self::$min_retry_delay && self::$min_retry_delay > 0) { $waittime = ($retry_count - self::$min_retry_delay + 1) * 5; echo "Waiting {$waittime} seconds before retry.\r\n"; DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'INFO', "Retry Attempt #{$retry_count}: Waiting {$waittime} seconds before retry."); usleep($waittime * 1000000); } // Assemble our URL $url = $this->url_base . $endpoint; // Initialize our Curl request $headers = $this->get_headers($endpoint, $data_string); $proxy = false; if ($this->proxies != false) { $proxy = $this->proxies[array_rand($this->proxies)]; } $ch = $this->init_request($url, $proxy); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); $log_msg = "Proxy: {$proxy['ip_address']}:{$proxy['port']}\r\n\r\n" . print_r($headers, true); $request_id = DataLoadLogDAO::logWebserviceRequest($this->db, $func_log_id, $url, $method, $proxy, $headers, $data_string); // Execute our request $start = microtime(true); $response_string = curl_exec($ch); $end = microtime(true); if (!$response_string) { $curl_error = curl_error($ch); } // cleans up the curl request curl_close($ch); $request_time = $end - $start; //echo "Request completed in ".$request_time." seconds\r\n"; // If our call failed if (!$response_string) { $log_msg = "Error Description: {$curl_error}\r\n\r\nProxy: {$proxy['ip_address']}:{$proxy['port']}<br/>\r\nURL: {$url}<br/>\r\nData: {$data_string}<br/>\r\n"; DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'ERROR', "Error occurred during curl request", $log_msg, 1); echo "Error occurred while getting Curl response.\r\n"; //echo "Proxy: {$proxy['ip_address']}:{$proxy['port']}<br/>\r\n"; //echo "URL: $url<br/>\r\n"; //echo "Data: $data_string<br/>\r\n\r\n"; ProxyDAO::countFailure($this->db, $proxy['id'], $request_time); // Retry if we haven't reached our max if (!$this->max_attempts_reached($retry_count)) { return $this->MakeRequest($endpoint, $data_string, $method, $retry_count + 1); } else { return false; } } // We send a header requesting a gzip encoded response, so try to decode it $decoded = gzdecode($response_string); // If we encountered an error in decoding, see what we can do with it if (!$decoded) { // Some of our proxies decode the gzip for us, so check to see if we've been decoded // If we have UTF-8 encoding already, then we might be OK after all if (mb_check_encoding($response_string, 'UTF-8')) { DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'WARNING', "Gzip decoding failed, but response is utf8 encoded. We'll try to use it.", $response_string); echo "Error occurred while decoding CURL response, but let's assume this is OK!\r\n"; // If we think we got a proxy error, then log it, and disable the proxy server. Otherwise return the response if (stripos($response_string, 'The maximum web proxy user limit has been reached') > 0) { DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'ERROR', "Proxy Limit Reached", null, 1); ProxyDAO::disableProxy($this->db, $proxy['id'], 'The maximum web proxy user limit has been reached'); } else { if (stripos($response_string, '<title>Access Den') > 0) { DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'ERROR', "Access Denied", null, 1); ProxyDAO::disableProxy($this->db, $proxy['id'], 'Access Denied Received'); } else { ProxyDAO::countSuccess($this->db, $proxy['id'], $request_time); // Since we have a valid string, try to decode the JSON response $json_array = json_decode($response_string, true); if (!$json_array) { DataLoadLogDAO::logWebserviceResponse($this->db, $request_id, $decoded, $request_time); DataLoadLogDAO::completeFunction($this->db, $func_log_id, 'Failed to Decode JSON Response'); return false; } DataLoadLogDAO::logWebserviceResponse($this->db, $request_id, $response_string, $request_time, $json_array); // Validate that the request completed successfully $this->ValidateResponse($json_array, $func_log_id, $request_id); return $json_array; } } } else { DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'ERROR', "Gzip decoding failed, and we don't know what to do with it. Retry this request.", $response_string, 1); echo "Error occurred while decoding CURL response, and we think this is a problem!\r\n"; ProxyDAO::countFailure($this->db, $proxy['id'], $request_time); } // If we made it this far then we need to retry if (!$this->max_attempts_reached($retry_count)) { DataLoadLogDAO::completeFunction($this->db, $func_log_id, 'Failed to Decode Response. Retrying.', 1); return $this->MakeRequest($endpoint, $data_string, $method, $retry_count + 1); } else { DataLoadLogDAO::completeFunction($this->db, $func_log_id, "Request Failed. Retry limit hit [{$retry_count}]. Quitting.", 1); return false; } } // If we made it this far, then we were successful, to let's log it as a success to our proxy ProxyDAO::countSuccess($this->db, $proxy['id'], $request_time); // Since we have a valid string, try to decode the JSON response $json_array = json_decode($decoded, true); if ($json_array === null) { DataLoadLogDAO::logWebserviceResponse($this->db, $request_id, $decoded, $request_time); DataLoadLogDAO::completeFunction($this->db, $func_log_id, 'Failed to Decode JSON Response', 1); return false; } DataLoadLogDAO::logWebserviceResponse($this->db, $request_id, $decoded, $request_time, $json_array); // Validate that the request completed successfully $status = $this->ValidateResponse($json_array, $func_log_id, $request_id); if ($status === 'retry') { DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'ERROR', "Validation returned [{$status}]. Retrying request...", $response_string, 1); echo "Validation returned [{$status}]. Retrying request...\n"; return $this->MakeRequest($endpoint, $data_string, $method, $retry_count + 1); } // Return the decoded string return $json_array; }
public function SwitchWorld($world_id) { /* POST /hc//index.php/json_gateway?svc=BatchController.call HTTP/1.1 x-newrelic-id: UgMDWFFADQYCUFFUBw== Accept: application/json Content-type: application/json; charset=UTF-8; X-Signature: 51931c0ffc90f6ac0e64e5f6bb1a7bbd X-Timestamp: 1424498999 User-Agent: Dalvik/1.6.0 (Linux; U; Android 4.2.2; Droid4X-MAC Build/JDQ39E) Host: gcand.gree-apps.net Connection: Keep-Alive Accept-Encoding: gzip Content-Length: 545 [{"transaction_time":"1424498999746","platform":"android","session_id":"6283633","start_sequence_num":1,"iphone_udid":"92639d40a61db79e7d8c01479b7638fc","wd_player_id":0,"locale":"en-US","_explicitType":"Session","client_build":"360","game_name":"HCGame","api_version":"1","mac_address":"14:10:9F:D6:7B:33","end_sequence_num":1,"req_id":1,"player_id":101019808535303,"language":"en","game_data_version":"hc_20150218_47131","client_version":"1.9.8"},[{"service":"world.world","method":"switch_world","_explicitType":"Command","params":[101013]}]] [{"transaction_time":"1410114994026","platform":"android","session_id":"51507 ","start_sequence_num":1,"iphone_udid":"8763af18eb4deace1840060a3bd9086b","wd_player_id":0,"locale":"en-US","_explicitType":"Session","client_build":"251","game_name":"HCGame","api_version":"1","mac_address":"c8:aa:21:40:0a:2a","end_sequence_num":1,"req_id":1,"player_id":101013596288193,"language":"en","game_data_version":"hc_20140903_38604","client_version":"1.8.4"},[{"service":"world.world","method":"join_world","_explicitType":"Command","params":[101001]}]] */ $log_seq = 0; $func_args = func_get_args(); $func_log_id = DataLoadLogDAO::startFunction($this->db, $this->data_load_id, __CLASS__, __FUNCTION__, $func_args); echo "Switching to World {$world_id}...\r\n"; $params = array(); $params['game_world_id'] = WorldDAO::getGameIdFromLocalId($this->db, $world_id); $response = $this->de->MakeRequest('SWITCH_WORLD', $params); if (!$response) { return false; } $success = $response['responses'][0]['return_value']['success']; if ($success != 1) { return false; } $this->world_id = $world_id; $this->player_id = $response['metadata']['player']['player_id']; DataLoadLogDAO::completeFunction($this->db, $func_log_id, "Switched to World {$this->world_id} as player {$this->player_id}"); // Authenticate into our new world return $this->Authenticate(); }
public function CompleteWorldMapExtraction() { $log_seq = 0; $func_log_id = DataLoadLogDAO::startFunction($this->db, $this->data_load_id, __CLASS__, __FUNCTION__); DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'DEBUG', 'Before Setting Resource Patch Counts'); $updates = WorldMapDAO::setResourcePatches($this->db, $this->auth->world_id); if ($this->db->hasError()) { echo "Error updating resource patches for world {$this->auth->world_id}: \r\n"; print_r($this->db->getError()); echo "\r\n"; $log_msg = print_r($this->db->getError(), true); DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'ERROR', "Error updating resource patches in World {$this->auth->world_id}", $log_msg, 1); } else { echo "Updated {$updates} bases resource patch counts\r\n"; DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'INFO', "Updated {$updates} bases resource patch counts"); } DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'DEBUG', 'Before Archiving Old Bases'); $archives = WorldMapDAO::archiveOldBases($this->db, $this->auth->world_id, $this->data_load_id); if ($archives !== false) { echo "Archived {$archives} bases from world {$this->auth->world_id} older than data load {$this->data_load_id}\r\n"; DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'INFO', "Archived {$archives} bases from world {$this->auth->world_id} older than data load {$this->data_load_id}"); } else { if ($this->db->hasError()) { echo "Error archiving bases from world {$this->auth->world_id} older than data load {$this->data_load_id}: \r\n"; print_r($this->db->getError()); echo "\r\n"; $log_msg = print_r($this->db->getError(), true); DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'ERROR', "Database Error while archiving bases from world {$this->auth->world_id} older than data load {$this->data_load_id}", $log_msg, 1); } else { echo "Error archiving bases from world {$this->auth->world_id}"; DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'ERROR', "Unknown error while archiving bases from world {$this->auth->world_id} older than data load {$this->data_load_id}", 1); } } DataLoadLogDAO::completeFunction($this->db, $func_log_id, "Updated {$updates} resource patches and archived {$archives} bases from world {$this->auth->world_id}"); return true; }
function SendWarningText($message, $ringer = false, $debug = 0) { // If we need to get the alert immediately, turn on the ringer if ($ringer) { $message = PgrmConfigDAO::getConfigProperty($this->db, 'SMTP', 'SERVER', 'value1') . ' | ' . $message; } $log_seq = 0; $func_args = func_get_args(); $func_log_id = DataLoadLogDAO::startFunction($this->db, $this->data_load_id, __CLASS__, __FUNCTION__, $func_args); //Create a new PHPMailer instance $mail = new PHPMailer(); //Tell PHPMailer to use SMTP $mail->isSMTP(); //Enable SMTP debugging // 0 = off (for production use) // 1 = client messages // 2 = client and server messages $mail->SMTPDebug = $debug; //Ask for HTML-friendly debug output $mail->Debugoutput = 'html'; //Set the hostname of the mail server $server = PgrmConfigDAO::getConfigProperties($this->db, 'SMTP', 'SERVER'); $mail->Host = $server['value1']; //Set the SMTP port number - likely to be 25, 465 or 587 $mail->Port = $server['value2']; //Whether to use SMTP authentication $mail->SMTPAuth = true; //Username to use for SMTP authentication $credentials = PgrmConfigDAO::getConfigProperties($this->db, 'SMTP', 'CREDENTIALS'); $mail->Username = $credentials['value1']; //Password to use for SMTP authentication $mail->Password = $credentials['value2']; //Set who the message is to be sent from $from_email = PgrmConfigDAO::getConfigProperties($this->db, 'SMTP', 'FROM_EMAIL'); $mail->setFrom($from_email['value1'], $from_email['value2']); //Set who the message is to be sent to $text_to = PgrmConfigDAO::getConfigProperties($this->db, 'SMTP', 'WARNING_TEXT_TO'); $mail->addAddress($text_to['value1'], $text_to['value2']); //Set the subject line $mail->Subject = ''; //Set the body of the message $mail->isHTML(false); $mail->Body = $message; //send the message, check for errors if (!$mail->send()) { echo "Mailer Error: " . $mail->ErrorInfo . "\r\n"; DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'ERROR', 'Error Sending Message', $mail->ErrorInfo, 1); DataLoadLogDAO::completeFunction($this->db, $func_log_id, 'Error Sending Message', 1); return false; } else { //echo "Message sent!"; DataLoadLogDAO::completeFunction($this->db, $func_log_id, 'Message Sent'); return true; } }
DataLoadDAO::startLoad($won->db, $won->data_load_id); // Get the Device ID to use (main account) if ($device_id == false) { $device_id = PgrmConfigDAO::getConfigProperty($won->db, 'value1', 'MAIN_DEVICE_ID'); } // Authenticate $auth_result = $won->Authenticate(false, $device_id, true); $last_session_time = time(); //$auth_result = json_decode(file_get_contents('auth_result.json'), true); //print_r($auth_result['responses'][0]['return_value']['player_towns']); //print_r($auth_result['responses'][0]['return_value']['player_town_reserves']); // Get an instance of our game operations class $game = $won->GetGameOperations(); $unit_map = $game::GetUnitMap(); $log_seq = 0; $func_log_id = DataLoadLogDAO::startFunction($won->db, $won->data_load_id, 'FlyTroops', 'Main'); while (true) { // Check configuration to make sure we aren't supposed to stop - this is the kill switch $stop = PgrmConfigDAO::getConfigProperty($won->db, 'value1', 'STOP_TROOP_FLYER'); if ($stop == 'Y') { echo "Stop Signal Detected!\n"; DataLoadLogDAO::logEvent2($won->db, $func_log_id, $log_seq++, 'INFO', 'Stop Signal Detected!'); break; } // If enough time has passed, start out with a new session if (time() - $last_session_time > $hours_between_sessions * 60 * 60) { DataLoadLogDAO::logEvent2($won->db, $func_log_id, $log_seq++, 'INFO', "At least {$hours_between_sessions} hour(s) have passed. Starting new session.\n"); // Save the data load for later, we don't want a new one $data_load_id = $won->data_load_id; // Re-initialize the WarOfNations object unset($won);
$seconds_pause_between_jeeps = 7; $seconds_pause_before_recall = 10; $seconds_pause_between_rounds = 5; // State variables $recall_fails_in_a_row = 0; $total_recall_failures = 0; // Initializing Operational Variables $time_before_second_cap = 0; $time_before_recall_hold = 0; // Authenticate ourselves //$auth_result = json_decode(file_get_contents('auth_result.json'), true); $auth_result = $won->Authenticate(false, 5, true); //print_r($auth_result['responses'][0]['return_value']['player_commanders']); // Get an instance of our game operations class $game = $won->GetGameOperations(); $func_log_id = DataLoadLogDAO::startFunction($won->db, $won->data_load_id, 'TrainCommanders', 'Main'); $quitting = false; $log_seq = 0; while (true) { // Sort commanders that are in the training base into groups $training_commanders = array(); $jeeping_commanders = array(); $extra_jeep_commanders = array(); $holding_commanders = array(); foreach ($auth_result['responses'][0]['return_value']['player_commanders'] as $comm) { // If the commander is in our designated training base and has energy if (array_key_exists('town_id', $comm) && $comm['town_id'] == $training_base_id && $comm['last_update_energy_value'] > 0) { // Determine whether this commander is for training or jeeping if (in_array($comm['commander_id'], $comms_to_train) || count($comms_to_train) == 0 && $comm['max_bonus_points'] == 10000) { if ($comm['last_update_energy_value'] > $training_comm_min_energy && $comm['level'] >= $comm_train_min_lvl && $comm['level'] <= $comm_train_max_lvl) { $training_commanders[] = $comm;
function SaveGuildLeaderboard($leader_data) { $log_seq = 0; $func_args = func_get_args(); $func_args[0] = 'Removed Hex Array. See WS Request Log.'; $func_log_id = DataLoadLogDAO::startFunction($this->db, $this->data_load_id, __CLASS__, __FUNCTION__, $func_args); $count = 0; foreach ($leader_data as $key => $leader) { $guild = new Guild(); $guild->world_id = $this->auth->world_id; $guild->data_load_id = $this->data_load_id; $guild->game_guild_id = $leader['guild_id']; if (array_key_exists('owner_id', $leader) && ($leader_id = PlayerDAO::getLocalIdFromGameId($this->db, $leader['owner_id']))) { $guild->leader_id = $leader_id; } $guild->guild_name = $leader['guild_name']; $guild->battle_points = $leader['score']; $guild->glory_points = $leader['glory_points']; $guild->members = $leader['member_count']; $id = GuildDAO::getLocalIdFromGameId($this->db, $guild->game_guild_id); if ($id) { $guild->id = $id; GuildDAO::updateGuild($this->db, $guild); } else { GuildDAO::insertGuild($this->db, $guild); } if ($this->db->hasError()) { echo 'Error saving guild: '; print_r($this->db->getError()); echo "\r\n"; $log_msg = var_dump($player) . "\r\n\r\n" . print_r($this->db->getError(), true); DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'ERROR', "Error Saving Guild: World [{$guild->world_id}], Guild: [{$guild->guild_name}]", $log_msg, 1); } else { $count++; } } DataLoadLogDAO::completeFunction($this->db, $func_log_id, "Saved {$count} Guilds"); }
public function Run() { $heartbeat_msg = '{"payload":{},"type":"heartbeat"}'; $log_seq = 0; $func_args = func_get_args(); $func_log_id = DataLoadLogDAO::startFunction($this->db, $this->data_load_id, __CLASS__, __FUNCTION__, $func_args); $seconds_between_heartbeat = 30; $closed = false; while (1) { DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'INFO', "Send heartbeat message"); echo "Sending: {$heartbeat_msg}\n----------\n"; $this->client->send($heartbeat_msg); $last_heartbeat = microtime(true); DataLoadDAO::operationComplete($this->db, $this->data_load_id); // This loop controls how many times we will try go receive in between heartbeats //for($i = 0; $i < 1; $i++) { // Continue reading until we run out of content to read, disconnect, or reach our heartbeat time while (1) { try { $message_handled = false; $opcode = ''; DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'INFO', "Listening..."); $seconds_since_heartbeat = microtime(true) - $last_heartbeat; echo "Seconds Since Heartbeat: {$seconds_since_heartbeat}\n"; $new_timeout = round($seconds_between_heartbeat - $seconds_since_heartbeat, 0); if ($new_timeout <= 0) { break; } echo "New Heartbeat Timeout: {$new_timeout} seconds\n"; echo "Receiving: "; $this->client->setTimeout($new_timeout); $data = $this->client->receive(); $opcode = $this->client->getLastOpcode(); echo "{$opcode}\n"; DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'MESSAGE', "Receive Complete [{$opcode}]"); //, $data); // Handle special cases here switch ($opcode) { case 'ping': // Respond with pong echo "Sending Pong\n----------\n"; DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'INFO', "Sending pong message"); $this->client->send('', 'pong'); $message_handled = true; break; case 'close': echo "Received Close. Disconnecting...\n"; DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'INFO', "Sending pong message"); $message_handled = true; $closed = true; break; } // If we already handled this message, go receive a new one if ($message_handled) { break; } try { echo "Trying to decode string\n"; $decoded_data = @gzdecode($data); if ($decoded_data == false) { echo "String not compressed\n{$data}\n==========\n"; DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'MESSAGE', "[{$opcode}] Message Not Compressed", $data); } else { $data = $decoded_data; echo "DECODED:\n{$data}\n==========\n"; DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'MESSAGE', "Decoded [{$opcode}] message", $data); } } catch (Exception $ex) { echo "Error\n"; } } catch (Exception $ex) { echo "No Data Found\n"; DataLoadLogDAO::logEvent2($this->db, $func_log_id, $log_seq++, 'ERROR', "No Data Found [{$opcode}]", $ex->getMessage(), 1); //usleep(5000000); //break; } } //} if ($closed) { break; } } DataLoadLogDAO::completeFunction($this->db, $func_log_id, 'Finished with Listener, this should never happen'); }
public function SendChatMessage($chat_stream, $message) { // [{"transaction_time":"1448671061854","platform":"android","session_id":"7968688","start_sequence_num":0,"iphone_udid":"8c9c72c38515837f4957843075bcac39","wd_player_id":0,"locale":"en-US","_explicitType":"Session","client_build":"489","game_name":"HCGame","api_version":"1","mac_address":"14:10:9F:D6:7B:33","end_sequence_num":0,"req_id":1,"player_id":101013624609676,"language":"en","game_data_version":"hc_NA_20151126_60629","client_version":"2.5.3.1"},[{"service":"chatservice.chatservice","method":"channels","_explicitType":"Command","params":["\/guild_101013232844480","2 concrete donated"]}]] $log_seq = 0; $func_args = func_get_args(); $func_log_id = DataLoadLogDAO::startFunction($this->db, $this->data_load_id, __CLASS__, __FUNCTION__, $func_args); echo "Sending '{$message}' to [{$chat_stream}]...\r\n"; $params = array(); $params['chat_stream'] = $chat_stream; $params['message'] = $message; $result = $this->de->MakeRequest('SEND_CHAT_MESSAGE', $params); if (!$result) { return false; } echo "Sent!\r\n\r\n"; DataLoadLogDAO::completeFunction($this->db, $func_log_id, "Successfully sent [{$message}] to [{$chat_stream}]"); return $result; }