Some refactoring and cleanup of the online request handling:

added setter/getter, renamed functions to have better names,
removed synchronousRequest from http_manager. Should be no
change in functionality.


git-svn-id: svn+ssh://svn.code.sf.net/p/supertuxkart/code/main/trunk@14967 178a84e3-b1eb-0310-8ba1-8eac791a3b58
This commit is contained in:
hikerstk
2014-01-08 12:08:46 +00:00
parent ff7a3d01c4
commit a1c964f71d
20 changed files with 630 additions and 477 deletions

View File

@@ -952,8 +952,7 @@ int handleCmdLine()
irr::core::stringw s;
Online::CurrentUser::SignInRequest* request =
Online::CurrentUser::get()->requestSignIn(login, password, false, false);
Online::HTTPManager::get()->synchronousRequest(request);
request->executeNow();
if (request->isSuccess())
{

View File

@@ -45,18 +45,18 @@ void GetPeerAddress::asynchronousUpdate()
if (m_state == NONE)
{
m_request = new Online::XMLRequest();
m_request->setURL((std::string)UserConfigParams::m_server_multiplayer + "address-management.php");
m_request->setParameter("id",Online::CurrentUser::get()->getID());
m_request->setParameter("token",Online::CurrentUser::get()->getToken());
m_request->setParameter("peer_id",m_peer_id);
m_request->setParameter("action","get");
m_request->setServerURL("address-management.php");
m_request->addParameter("id",Online::CurrentUser::get()->getID());
m_request->addParameter("token",Online::CurrentUser::get()->getToken());
m_request->addParameter("peer_id",m_peer_id);
m_request->addParameter("action","get");
Online::HTTPManager::get()->addRequest(m_request);
m_state = REQUEST_PENDING;
}
else if (m_state == REQUEST_PENDING && m_request->isDone())
{
const XMLNode * result = m_request->getResult();
const XMLNode * result = m_request->getXMLData();
std::string rec_success;
if(result->get("success", &rec_success))

View File

@@ -42,17 +42,17 @@ void HidePublicAddress::asynchronousUpdate()
if (m_state == NONE)
{
m_request = new Online::XMLRequest();
m_request->setURL((std::string)UserConfigParams::m_server_multiplayer + "address-management.php");
m_request->setParameter("id",Online::CurrentUser::get()->getID());
m_request->setParameter("token",Online::CurrentUser::get()->getToken());
m_request->setParameter("action","unset");
m_request->setServerURL("address-management.php");
m_request->addParameter("id",Online::CurrentUser::get()->getID());
m_request->addParameter("token",Online::CurrentUser::get()->getToken());
m_request->addParameter("action","unset");
Online::HTTPManager::get()->addRequest(m_request);
m_state = REQUEST_PENDING;
}
else if (m_state == REQUEST_PENDING && m_request->isDone())
{
const XMLNode * result = m_request->getResult();
const XMLNode * result = m_request->getXMLData();
std::string rec_success;
if(result->get("success", &rec_success))

View File

@@ -44,17 +44,17 @@ void QuickJoinProtocol::asynchronousUpdate()
{
TransportAddress addr = NetworkManager::getInstance()->getPublicAddress();
m_request = new Online::XMLRequest();
m_request->setURL((std::string)UserConfigParams::m_server_multiplayer + "address-management.php");
m_request->setParameter("id",Online::CurrentUser::get()->getID());
m_request->setParameter("token",Online::CurrentUser::get()->getToken());
m_request->setParameter("action","quick-join");
m_request->setServerURL("address-management.php");
m_request->addParameter("id",Online::CurrentUser::get()->getID());
m_request->addParameter("token",Online::CurrentUser::get()->getToken());
m_request->addParameter("action","quick-join");
Online::HTTPManager::get()->addRequest(m_request);
m_state = REQUEST_PENDING;
}
else if (m_state == REQUEST_PENDING && m_request->isDone())
{
const XMLNode * result = m_request->getResult();
const XMLNode * result = m_request->getXMLData();
std::string rec_success;
TransportAddress* res = static_cast<TransportAddress*>(m_callback_object);

View File

@@ -44,11 +44,11 @@ void RequestConnection::asynchronousUpdate()
case NONE:
{
m_request = new Online::CurrentUser::ServerJoinRequest();
m_request->setURL((std::string)UserConfigParams::m_server_multiplayer + "address-management.php");
m_request->setParameter("id",Online::CurrentUser::get()->getID());
m_request->setParameter("token",Online::CurrentUser::get()->getToken());
m_request->setParameter("server_id",m_server_id);
m_request->setParameter("action","request-connection");
m_request->setServerURL("address-management.php");
m_request->addParameter("id",Online::CurrentUser::get()->getID());
m_request->addParameter("token",Online::CurrentUser::get()->getToken());
m_request->addParameter("server_id",m_server_id);
m_request->addParameter("action","request-connection");
Online::HTTPManager::get()->addRequest(m_request);
m_state = REQUEST_PENDING;
@@ -58,7 +58,7 @@ void RequestConnection::asynchronousUpdate()
{
if (!m_request->isDone())
return;
const XMLNode * result = m_request->getResult();
const XMLNode * result = m_request->getXMLData();
std::string rec_success;
if(result->get("success", &rec_success))

View File

@@ -183,17 +183,17 @@ void ServerLobbyRoomProtocol::checkIncomingConnectionRequests()
last_poll_time = StkTime::getRealTime();
TransportAddress addr = NetworkManager::getInstance()->getPublicAddress();
Online::XMLRequest* request = new Online::XMLRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "address-management.php");
request->setParameter("id",Online::CurrentUser::get()->getProfile()->getID());
request->setParameter("token",Online::CurrentUser::get()->getToken());
request->setParameter("address",addr.ip);
request->setParameter("port",addr.port);
request->setParameter("action","poll-connection-requests");
request->setServerURL("address-management.php");
request->addParameter("id",Online::CurrentUser::get()->getProfile()->getID());
request->addParameter("token",Online::CurrentUser::get()->getToken());
request->addParameter("address",addr.ip);
request->addParameter("port",addr.port);
request->addParameter("action","poll-connection-requests");
Online::HTTPManager::get()->synchronousRequest(request);
request->executeNow();
assert(request->isDone());
const XMLNode * result = request->getResult();
const XMLNode * result = request->getXMLData();
std::string rec_success;
if(result->get("success", &rec_success))
{

View File

@@ -43,13 +43,13 @@ void ShowPublicAddress::asynchronousUpdate()
{
TransportAddress addr = NetworkManager::getInstance()->getPublicAddress();
m_request = new Online::XMLRequest();
m_request->setURL((std::string)UserConfigParams::m_server_multiplayer + "address-management.php");
m_request->setParameter("id",Online::CurrentUser::get()->getID());
m_request->setParameter("token",Online::CurrentUser::get()->getToken());
m_request->setParameter("address",addr.ip);
m_request->setParameter("port",addr.port);
m_request->setParameter("private_port",NetworkManager::getInstance()->getHost()->getPort());
m_request->setParameter("action","set");
m_request->setServerURL("address-management.php");
m_request->addParameter("id",Online::CurrentUser::get()->getID());
m_request->addParameter("token",Online::CurrentUser::get()->getToken());
m_request->addParameter("address",addr.ip);
m_request->addParameter("port",addr.port);
m_request->addParameter("private_port",NetworkManager::getInstance()->getHost()->getPort());
m_request->addParameter("action","set");
Log::info("ShowPublicAddress", "Showing addr %u and port %d", addr.ip, addr.port);
Online::HTTPManager::get()->addRequest(m_request);
@@ -57,7 +57,7 @@ void ShowPublicAddress::asynchronousUpdate()
}
else if (m_state == REQUEST_PENDING && m_request->isDone())
{
const XMLNode * result = m_request->getResult();
const XMLNode * result = m_request->getXMLData();
std::string rec_success;
if(result->get("success", &rec_success))

View File

@@ -42,14 +42,14 @@ void StartServer::asynchronousUpdate()
{
TransportAddress addr = NetworkManager::getInstance()->getPublicAddress();
m_request = new Online::XMLRequest();
m_request->setURL((std::string)UserConfigParams::m_server_multiplayer + "address-management.php");
m_request->setParameter("id",Online::CurrentUser::get()->getID());
m_request->setParameter("token",Online::CurrentUser::get()->getToken());
m_request->setParameter("address",addr.ip);
m_request->setParameter("port",addr.port);
m_request->setParameter("private_port",NetworkManager::getInstance()->getHost()->getPort());
m_request->setParameter("max_players",UserConfigParams::m_server_max_players);
m_request->setParameter("action","start-server");
m_request->setServerURL("address-management.php");
m_request->addParameter("id",Online::CurrentUser::get()->getID());
m_request->addParameter("token",Online::CurrentUser::get()->getToken());
m_request->addParameter("address",addr.ip);
m_request->addParameter("port",addr.port);
m_request->addParameter("private_port",NetworkManager::getInstance()->getHost()->getPort());
m_request->addParameter("max_players",UserConfigParams::m_server_max_players);
m_request->addParameter("action","start-server");
Log::info("ShowPublicAddress", "Showing addr %u and port %d", addr.ip, addr.port);
Online::HTTPManager::get()->addRequest(m_request);
@@ -57,7 +57,7 @@ void StartServer::asynchronousUpdate()
}
else if (m_state == REQUEST_PENDING && m_request->isDone())
{
const XMLNode * result = m_request->getResult();
const XMLNode * result = m_request->getXMLData();
std::string rec_success;
if(result->get("success", &rec_success))

View File

@@ -47,12 +47,12 @@ void StopServer::asynchronousUpdate()
{
TransportAddress addr = NetworkManager::getInstance()->getPublicAddress();
m_request = new Online::XMLRequest();
m_request->setURL((std::string)UserConfigParams::m_server_multiplayer + "address-management.php");
m_request->setParameter("id",Online::CurrentUser::get()->getID());
m_request->setParameter("token",Online::CurrentUser::get()->getToken());
m_request->setParameter("address",addr.ip);
m_request->setParameter("port",addr.port);
m_request->setParameter("action","stop-server");
m_request->setServerURL( "address-management.php");
m_request->addParameter("id",Online::CurrentUser::get()->getID());
m_request->addParameter("token",Online::CurrentUser::get()->getToken());
m_request->addParameter("address",addr.ip);
m_request->addParameter("port",addr.port);
m_request->addParameter("action","stop-server");
Log::info("StopServer", "address %u, port %d", addr.ip, addr.port);
Online::HTTPManager::get()->addRequest(m_request);
@@ -60,7 +60,7 @@ void StopServer::asynchronousUpdate()
}
else if (m_state == REQUEST_PENDING && m_request->isDone())
{
const XMLNode * result = m_request->getResult();
const XMLNode * result = m_request->getXMLData();
std::string rec_success;
if(result->get("success", &rec_success))

View File

@@ -41,7 +41,8 @@
using namespace Online;
namespace Online{
namespace Online
{
static CurrentUser* current_user_singleton(NULL);
CurrentUser* CurrentUser::get()
@@ -72,10 +73,10 @@ namespace Online{
{
assert(m_state == US_SIGNED_OUT || m_state == US_GUEST);
XMLRequest * request = new XMLRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("recovery"));
request->setParameter("username", username);
request->setParameter("email", email);
request->setServerURL("client-user.php");
request->addParameter("action", std::string("recovery"));
request->addParameter("username", username);
request->addParameter("email", email);
HTTPManager::get()->addRequest(request);
return request;
}
@@ -89,13 +90,13 @@ namespace Online{
{
assert(m_state == US_SIGNED_OUT || m_state == US_GUEST);
XMLRequest * request = new XMLRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("register"));
request->setParameter("username", username);
request->setParameter("password", password);
request->setParameter("password_confirm", password_confirm);
request->setParameter("email", email);
request->setParameter("terms", std::string("on"));
request->setServerURL("client-user.php");
request->addParameter("action", std::string("register"));
request->addParameter("username", username);
request->addParameter("password", password);
request->addParameter("password_confirm", password_confirm);
request->addParameter("email", email);
request->addParameter("terms", std::string("on"));
HTTPManager::get()->addRequest(request);
return request;
}
@@ -107,10 +108,10 @@ namespace Online{
if(m_state == US_SIGNED_OUT && UserConfigParams::m_saved_session)
{
request = new SignInRequest(true);
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action",std::string("saved-session"));
request->setParameter("userid", UserConfigParams::m_saved_user);
request->setParameter("token", UserConfigParams::m_saved_token.c_str());
request->setServerURL("client-user.php");
request->addParameter("action",std::string("saved-session"));
request->addParameter("userid", UserConfigParams::m_saved_user);
request->addParameter("token", UserConfigParams::m_saved_token.c_str());
HTTPManager::get()->addRequest(request);
m_state = US_SIGNING_IN;
}
@@ -123,11 +124,11 @@ namespace Online{
assert(m_state == US_SIGNED_OUT);
m_save_session = save_session;
SignInRequest * request = new SignInRequest(request_now);
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action",std::string("connect"));
request->setParameter("username",username);
request->setParameter("password",password);
request->setParameter("save-session", StringUtils::boolstr(save_session));
request->setServerURL("client-user.php");
request->addParameter("action",std::string("connect"));
request->addParameter("username",username);
request->addParameter("password",password);
request->addParameter("save-session", StringUtils::boolstr(save_session));
if (request_now)
{
HTTPManager::get()->addRequest(request);
@@ -172,16 +173,16 @@ namespace Online{
void CurrentUser::SignInRequest::callback()
{
CurrentUser::get()->signIn(m_success, m_result);
CurrentUser::get()->signIn(isSuccess(), getXMLData());
if(GUIEngine::ModalDialog::isADialogActive())
{
LoginDialog * dialog = dynamic_cast<LoginDialog*>(GUIEngine::ModalDialog::getCurrent());
if(dialog != NULL)
{
if(m_success)
if(isSuccess())
dialog->success();
else
dialog->error(m_info);
dialog->error(getInfo());
}
}
}
@@ -193,21 +194,21 @@ namespace Online{
{
assert(m_state == US_SIGNED_IN);
ServerCreationRequest * request = new ServerCreationRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("create_server"));
request->setParameter("token", getToken());
request->setParameter("userid", getID());
request->setParameter("name", name);
request->setParameter("max_players", max_players);
request->setServerURL("client-user.php");
request->addParameter("action", std::string("create_server"));
request->addParameter("token", getToken());
request->addParameter("userid", getID());
request->addParameter("name", name);
request->addParameter("max_players", max_players);
HTTPManager::get()->addRequest(request);
return request;
}
void CurrentUser::ServerCreationRequest::callback()
{
if(m_success)
if(isSuccess())
{
Server * server = new Server(*m_result->getNode("server"));
Server * server = new Server(*getXMLData()->getNode("server"));
ServersManager::get()->addServer(server);
m_created_server_id = server->getServerId();
}
@@ -217,10 +218,10 @@ namespace Online{
void CurrentUser::requestSignOut(){
assert(m_state == US_SIGNED_IN || m_state == US_GUEST);
SignOutRequest * request = new SignOutRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action",std::string("disconnect"));
request->setParameter("token", getToken());
request->setParameter("userid", getID());
request->setServerURL("client-user.php");
request->addParameter("action",std::string("disconnect"));
request->addParameter("token", getToken());
request->addParameter("userid", getID());
HTTPManager::get()->addRequest(request);
m_state = US_SIGNING_OUT;
}
@@ -243,7 +244,7 @@ namespace Online{
void CurrentUser::SignOutRequest::callback()
{
CurrentUser::get()->signOut(m_success, m_result);
CurrentUser::get()->signOut(isSuccess(), getXMLData());
}
// ============================================================================
@@ -253,11 +254,11 @@ namespace Online{
{
assert(m_state == US_SIGNED_IN || m_state == US_GUEST);
ServerJoinRequest * request = new ServerJoinRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "address-management.php");
request->setParameter("action",std::string("request-connection"));
request->setParameter("token", getToken());
request->setParameter("id", getID());
request->setParameter("server_id", server_id);
request->setServerURL("address-management.php");
request->addParameter("action",std::string("request-connection"));
request->addParameter("token", getToken());
request->addParameter("id", getID());
request->addParameter("server_id", server_id);
if (request_now)
HTTPManager::get()->addRequest(request);
return request;
@@ -265,10 +266,10 @@ namespace Online{
void CurrentUser::ServerJoinRequest::callback()
{
if(m_success)
if(isSuccess())
{
uint32_t server_id;
m_result->get("serverid", &server_id);
getXMLData()->get("serverid", &server_id);
ServersManager::get()->setJoinedServer(server_id);
}
//FIXME needs changes for actual valid joining
@@ -280,11 +281,11 @@ namespace Online{
{
assert(m_state == US_SIGNED_IN);
XMLRequest * request = new XMLRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("get-addon-vote"));
request->setParameter("token", getToken());
request->setParameter("userid", getID());
request->setParameter("addonid", addon_id.substr(6));
request->setServerURL("client-user.php");
request->addParameter("action", std::string("get-addon-vote"));
request->addParameter("token", getToken());
request->addParameter("userid", getID());
request->addParameter("addonid", addon_id.substr(6));
HTTPManager::get()->addRequest(request);
return request;
}
@@ -298,11 +299,11 @@ namespace Online{
{
assert(m_state == US_SIGNED_IN);
XMLRequest * request = new XMLRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("user-search"));
request->setParameter("token", getToken());
request->setParameter("userid", getID());
request->setParameter("search-string", search_string);
request->setServerURL("client-user.php");
request->addParameter("action", std::string("user-search"));
request->addParameter("token", getToken());
request->addParameter("userid", getID());
request->addParameter("search-string", search_string);
HTTPManager::get()->addRequest(request);
return request;
}
@@ -317,12 +318,12 @@ namespace Online{
{
assert(m_state == US_SIGNED_IN);
CurrentUser::SetAddonVoteRequest * request = new CurrentUser::SetAddonVoteRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("set-addon-vote"));
request->setParameter("token", getToken());
request->setParameter("userid", getID());
request->setParameter("addonid", addon_id.substr(6));
request->setParameter("rating", rating);
request->setServerURL("client-user.php");
request->addParameter("action", std::string("set-addon-vote"));
request->addParameter("token", getToken());
request->addParameter("userid", getID());
request->addParameter("addonid", addon_id.substr(6));
request->addParameter("rating", rating);
HTTPManager::get()->addRequest(request);
return request;
}
@@ -332,12 +333,12 @@ namespace Online{
*/
void CurrentUser::SetAddonVoteRequest::callback()
{
if(m_success)
if(isSuccess())
{
std::string addon_id;
m_result->get("addon-id", &addon_id);
getXMLData()->get("addon-id", &addon_id);
float average;
m_result->get("new-average", &average);
getXMLData()->get("new-average", &average);
addons_manager->getAddon(Addon::createAddonId(addon_id))->setRating(average);
}
}
@@ -351,11 +352,11 @@ namespace Online{
{
assert(m_state == US_SIGNED_IN);
CurrentUser::FriendRequest * request = new CurrentUser::FriendRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("friend-request"));
request->setParameter("token", getToken());
request->setParameter("userid", getID());
request->setParameter("friendid", friend_id);
request->setServerURL("client-user.php");
request->addParameter("action", std::string("friend-request"));
request->addParameter("token", getToken());
request->addParameter("userid", getID());
request->addParameter("friendid", friend_id);
HTTPManager::get()->addRequest(request);
}
@@ -365,9 +366,9 @@ namespace Online{
void CurrentUser::FriendRequest::callback()
{
uint32_t id(0);
m_result->get("friendid", &id);
getXMLData()->get("friendid", &id);
irr::core::stringw info_text("");
if(m_success)
if(isSuccess())
{
CurrentUser::get()->getProfile()->addFriend(id);
ProfileManager::get()->getProfileByID(id)->setRelationInfo(new Profile::RelationInfo(_("Today"), false, true, false));
@@ -375,8 +376,8 @@ namespace Online{
info_text = _("Friend request send!");
}
else
info_text = m_info;
GUIEngine::DialogQueue::get()->pushDialog( new UserInfoDialog(id, info_text,!m_success, true), true);
info_text = getInfo();
GUIEngine::DialogQueue::get()->pushDialog( new UserInfoDialog(id, info_text,!isSuccess(), true), true);
}
// ============================================================================
@@ -388,11 +389,11 @@ namespace Online{
{
assert(m_state == US_SIGNED_IN);
CurrentUser::AcceptFriendRequest * request = new CurrentUser::AcceptFriendRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("accept-friend-request"));
request->setParameter("token", getToken());
request->setParameter("userid", getID());
request->setParameter("friendid", friend_id);
request->setServerURL("client-user.php");
request->addParameter("action", std::string("accept-friend-request"));
request->addParameter("token", getToken());
request->addParameter("userid", getID());
request->addParameter("friendid", friend_id);
HTTPManager::get()->addRequest(request);
}
@@ -402,9 +403,9 @@ namespace Online{
void CurrentUser::AcceptFriendRequest::callback()
{
uint32_t id(0);
m_result->get("friendid", &id);
getXMLData()->get("friendid", &id);
irr::core::stringw info_text("");
if(m_success)
if(isSuccess())
{
Profile * profile = ProfileManager::get()->getProfileByID(id);
profile->setFriend();
@@ -413,8 +414,8 @@ namespace Online{
info_text = _("Friend request accepted!");
}
else
info_text = m_info;
GUIEngine::DialogQueue::get()->pushDialog( new UserInfoDialog(id, info_text,!m_success, true), true);
info_text = getInfo();
GUIEngine::DialogQueue::get()->pushDialog( new UserInfoDialog(id, info_text,!isSuccess(), true), true);
}
// ============================================================================
@@ -426,11 +427,11 @@ namespace Online{
{
assert(m_state == US_SIGNED_IN);
CurrentUser::DeclineFriendRequest * request = new CurrentUser::DeclineFriendRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("decline-friend-request"));
request->setParameter("token", getToken());
request->setParameter("userid", getID());
request->setParameter("friendid", friend_id);
request->setServerURL("client-user.php");
request->addParameter("action", std::string("decline-friend-request"));
request->addParameter("token", getToken());
request->addParameter("userid", getID());
request->addParameter("friendid", friend_id);
HTTPManager::get()->addRequest(request);
}
@@ -440,9 +441,9 @@ namespace Online{
void CurrentUser::DeclineFriendRequest::callback()
{
uint32_t id(0);
m_result->get("friendid", &id);
getXMLData()->get("friendid", &id);
irr::core::stringw info_text("");
if(m_success)
if(isSuccess())
{
CurrentUser::get()->getProfile()->removeFriend(id);
ProfileManager::get()->moveToCache(id);
@@ -451,8 +452,8 @@ namespace Online{
info_text = _("Friend request declined!");
}
else
info_text = m_info;
GUIEngine::DialogQueue::get()->pushDialog( new UserInfoDialog(id, info_text,!m_success, true), true);
info_text = getInfo();
GUIEngine::DialogQueue::get()->pushDialog( new UserInfoDialog(id, info_text,!isSuccess(), true), true);
}
@@ -465,11 +466,11 @@ namespace Online{
{
assert(m_state == US_SIGNED_IN);
CurrentUser::CancelFriendRequest * request = new CurrentUser::CancelFriendRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("cancel-friend-request"));
request->setParameter("token", getToken());
request->setParameter("userid", getID());
request->setParameter("friendid", friend_id);
request->setServerURL("client-user.php");
request->addParameter("action", std::string("cancel-friend-request"));
request->addParameter("token", getToken());
request->addParameter("userid", getID());
request->addParameter("friendid", friend_id);
HTTPManager::get()->addRequest(request);
}
@@ -479,9 +480,9 @@ namespace Online{
void CurrentUser::CancelFriendRequest::callback()
{
uint32_t id(0);
m_result->get("friendid", &id);
getXMLData()->get("friendid", &id);
irr::core::stringw info_text("");
if(m_success)
if(isSuccess())
{
CurrentUser::get()->getProfile()->removeFriend(id);
ProfileManager::get()->moveToCache(id);
@@ -490,8 +491,8 @@ namespace Online{
info_text = _("Friend request cancelled!");
}
else
info_text = m_info;
GUIEngine::DialogQueue::get()->pushDialog( new UserInfoDialog(id, info_text,!m_success, true), true);
info_text = getInfo();
GUIEngine::DialogQueue::get()->pushDialog( new UserInfoDialog(id, info_text,!isSuccess(), true), true);
}
@@ -504,11 +505,11 @@ namespace Online{
{
assert(m_state == US_SIGNED_IN);
CurrentUser::RemoveFriendRequest * request = new CurrentUser::RemoveFriendRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("remove-friend"));
request->setParameter("token", getToken());
request->setParameter("userid", getID());
request->setParameter("friendid", friend_id);
request->setServerURL("client-user.php");
request->addParameter("action", std::string("remove-friend"));
request->addParameter("token", getToken());
request->addParameter("userid", getID());
request->addParameter("friendid", friend_id);
HTTPManager::get()->addRequest(request);
}
@@ -518,9 +519,9 @@ namespace Online{
void CurrentUser::RemoveFriendRequest::callback()
{
uint32_t id(0);
m_result->get("friendid", &id);
getXMLData()->get("friendid", &id);
irr::core::stringw info_text("");
if(m_success)
if(isSuccess())
{
CurrentUser::get()->getProfile()->removeFriend(id);
ProfileManager::get()->moveToCache(id);
@@ -529,8 +530,8 @@ namespace Online{
info_text = _("Friend removed!");
}
else
info_text = m_info;
GUIEngine::DialogQueue::get()->pushDialog( new UserInfoDialog(id, info_text,!m_success, true), true);
info_text = getInfo();
GUIEngine::DialogQueue::get()->pushDialog( new UserInfoDialog(id, info_text,!isSuccess(), true), true);
}
@@ -547,12 +548,12 @@ namespace Online{
{
assert(m_state == US_SIGNED_IN);
ChangePasswordRequest * request = new ChangePasswordRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("change_password"));
request->setParameter("userid", getID());
request->setParameter("current", current_password);
request->setParameter("new1", new_password);
request->setParameter("new2", new_password_ver);
request->setServerURL("client-user.php");
request->addParameter("action", std::string("change_password"));
request->addParameter("userid", getID());
request->addParameter("current", current_password);
request->addParameter("new1", new_password);
request->addParameter("new2", new_password_ver);
HTTPManager::get()->addRequest(request);
}
@@ -566,10 +567,10 @@ namespace Online{
ChangePasswordDialog * dialog = dynamic_cast<ChangePasswordDialog*>(GUIEngine::ModalDialog::getCurrent());
if(dialog != NULL)
{
if(m_success)
if(isSuccess())
dialog->success();
else
dialog->error(m_info);
dialog->error(getInfo());
}
}
}
@@ -581,10 +582,10 @@ namespace Online{
{
assert(m_state == US_SIGNED_IN);
CurrentUser::PollRequest * request = new CurrentUser::PollRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("poll"));
request->setParameter("token", getToken());
request->setParameter("userid", getID());
request->setServerURL("client-user.php");
request->addParameter("action", std::string("poll"));
request->addParameter("token", getToken());
request->addParameter("userid", getID());
HTTPManager::get()->addRequest(request);
}
@@ -593,14 +594,14 @@ namespace Online{
*/
void CurrentUser::PollRequest::callback()
{
if(m_success)
if(isSuccess())
{
if(!CurrentUser::get()->isRegisteredUser())
return;
if(CurrentUser::get()->getProfile()->hasFetchedFriends())
{
std::string online_friends_string("");
if(m_result->get("online", &online_friends_string) == 1)
if(getXMLData()->get("online", &online_friends_string) == 1)
{
std::vector<uint32_t> online_friends = StringUtils::splitToUInt(online_friends_string, ' ');
bool went_offline = false;
@@ -673,9 +674,9 @@ namespace Online{
}
int friend_request_count = 0;
for(unsigned int i = 0; i < m_result->getNumNodes(); i++)
for(unsigned int i = 0; i < getXMLData()->getNumNodes(); i++)
{
const XMLNode * node = m_result->getNode(i);
const XMLNode * node = getXMLData()->getNode(i);
if(node->getName() == "new_friend_request")
{
Profile::RelationInfo * ri = new Profile::RelationInfo("New", false, true, true);
@@ -713,10 +714,10 @@ namespace Online{
if(isRegisteredUser())
{
HTTPRequest * request = new HTTPRequest(true, HTTPManager::HTTP_MAX_PRIORITY);
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("client-quit"));
request->setParameter("token", getToken());
request->setParameter("userid", getID());
request->setServerURL("client-user.php");
request->addParameter("action", std::string("client-quit"));
request->addParameter("token", getToken());
request->addParameter("userid", getID());
HTTPManager::get()->addRequest(request);
}
}
@@ -731,11 +732,11 @@ namespace Online{
if(isRegisteredUser())
{
HTTPRequest * request = new HTTPRequest(true);
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("achieving"));
request->setParameter("token", getToken());
request->setParameter("userid", getID());
request->setParameter("achievementid", achievement_id);
request->setServerURL("client-user.php");
request->addParameter("action", std::string("achieving"));
request->addParameter("token", getToken());
request->addParameter("userid", getID());
request->addParameter("achievementid", achievement_id);
HTTPManager::get()->addRequest(request);
}
}

View File

@@ -30,7 +30,8 @@
#include <string>
#include <assert.h>
namespace Online{
namespace Online
{
// ============================================================================

View File

@@ -43,6 +43,7 @@ namespace Online{
static HTTPManager * http_singleton = NULL;
// ------------------------------------------------------------------------
HTTPManager* HTTPManager::get()
{
if (http_singleton == NULL)
@@ -52,6 +53,9 @@ namespace Online{
return http_singleton;
} // get
// ------------------------------------------------------------------------
/** Deletes the http manager.
*/
void HTTPManager::deallocate()
{
if (http_singleton != NULL)
@@ -61,20 +65,25 @@ namespace Online{
}
} // deallocate
// ------------------------------------------------------------------------
/** Checks if the http manager is running.
*/
bool HTTPManager::isRunning()
{
return http_singleton != NULL;
}
} // isRunning
// ------------------------------------------------------------------------
HTTPManager::HTTPManager(){
HTTPManager::HTTPManager()
{
curl_global_init(CURL_GLOBAL_DEFAULT);
pthread_cond_init(&m_cond_request, NULL);
m_abort.setAtomic(false);
m_time_since_poll = MENU_POLLING_INTERVAL * 0.9;
}
// ============================================================================
// ------------------------------------------------------------------------
HTTPManager::~HTTPManager(){
m_thread_id.lock();
pthread_join(*m_thread_id.getData(), NULL);
@@ -85,7 +94,7 @@ namespace Online{
}
// ---------------------------------------------------------------------------
// ------------------------------------------------------------------------
/** Start the actual network thread. This can not be done as part of
* the constructor, since the assignment to the global network_http
* variable has not been assigned at that stage, and the thread might
@@ -110,14 +119,14 @@ namespace Online{
delete m_thread_id.getData();
m_thread_id.unlock();
m_thread_id.setAtomic(0);
Log::error("HTTP Manager", "Could not create thread, error=%d.\n", errno);
Log::error("HTTP Manager", "Could not create thread, error=%d.",
errno);
}
pthread_attr_destroy(&attr);
CurrentUser::get()->requestSavedSession();
} // startNetworkThread
// ---------------------------------------------------------------------------
// ------------------------------------------------------------------------
/** This function inserts a high priority request to quit into the request
* queue of the network thead, and also aborts any ongoing download.
* Separating this allows more time for the thread to finish cleanly,
@@ -136,8 +145,7 @@ namespace Online{
addRequest(new Request(true, HTTP_MAX_PRIORITY, Request::RT_QUIT));
} // stopNetworkThread
// ----------------------------------------------------------------------------
// ------------------------------------------------------------------------
/** Signals to the progress function to request any ongoing download to be
* cancelled. This function can also be called if there is actually no
* download atm. The function progressDownload checks m_abort and will
@@ -149,15 +157,14 @@ namespace Online{
// be sure that HTTP_MAX_PRIORITY requests still get executed.
} // cancelAllDownloads
// ----------------------------------------------------------------------------
// ------------------------------------------------------------------------
/** Inserts a request into the queue of all requests. The request will be
* sorted by priority.
* \param request The pointer to the new request to insert.
*/
void HTTPManager::addRequest(Request *request)
{
assert(request->isAllowedToAdd());
assert(request->isPreparing());
request->setBusy();
m_request_queue.lock();
m_request_queue.getData().push(request);
@@ -166,21 +173,7 @@ namespace Online{
m_request_queue.unlock();
} // addRequest
// ----------------------------------------------------------------------------
/** Immediately performs a request synchronously
* \param request The pointer to the request to execute.
*/
void HTTPManager::synchronousRequest(Request *request)
{
assert(request->isAllowedToAdd());
request->setBusy();
request->execute();
request->callback();
request->setDone();
} // synchronousRequest
// ---------------------------------------------------------------------------
// ------------------------------------------------------------------------
/** The actual main loop, which is started as a separate thread from the
* constructor. After testing for a new server, fetching news, the list
* of packages to download, it will wait for commands to be issued.
@@ -230,22 +223,22 @@ namespace Online{
return 0;
} // mainLoop
// ----------------------------------------------------------------------------
// ------------------------------------------------------------------------
/** Inserts a request into the queue of results.
* \param request The pointer to the request to insert.
*/
void HTTPManager::addResult(Online::Request *request)
{
assert(request->isBusy());
assert(request->hasBeenExecuted());
m_result_queue.lock();
m_result_queue.getData().push(request);
m_result_queue.unlock();
}
} // addResult
// ----------------------------------------------------------------------------
/**
* Takes a request out of the result queue, if any is present.
* Calls the callback method of the request and takes care of memory management if necessary.
// ------------------------------------------------------------------------
/** Takes a request out of the result queue, if any is present.
* Calls the callback method of the request and takes care of memory
* management if necessary.
*/
void HTTPManager::handleResultQueue()
{
@@ -270,12 +263,12 @@ namespace Online{
}
}
// ----------------------------------------------------------------------------
/**
* Should be called every frame and takes care of processing the result queue
* and polling the database server if a user is signed in.
// ------------------------------------------------------------------------
/** Should be called every frame and takes care of processing the result
* queue and polling the database server if a user is signed in.
*/
void HTTPManager::update(float dt){
void HTTPManager::update(float dt)
{
handleResultQueue();
//Database polling starts here, only needed for registered users
@@ -292,7 +285,7 @@ namespace Online{
CurrentUser::get()->requestPoll();
}
}
} // update
} // namespace Online

View File

@@ -1,8 +1,8 @@
//
// SuperTuxKart - a fun racing game with go-kart
// Copyright (C) 2010 Lucas Baudin
// 2011 Joerg Henrichs
// 2013 Glenn De Jonghe
// Copyright (C) 2010-2014 Lucas Baudin
// 2011-2014 Joerg Henrichs
// 2013-2014 Glenn De Jonghe
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
@@ -90,7 +90,6 @@ namespace Online{
static void deallocate();
static bool isRunning();
void synchronousRequest(Online::Request *request);
void addRequest(Online::Request *request);
void cancelAllDownloads();
void startNetworkThread();

View File

@@ -141,20 +141,21 @@ namespace Online{
{
assert(CurrentUser::get()->isRegisteredUser() && !m_is_current_user);
AchievementsRequest * request = new AchievementsRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action",std::string("get-achievements"));
request->setParameter("token", CurrentUser::get()->getToken());
request->setParameter("userid", CurrentUser::get()->getID());
request->setParameter("visitingid", m_id);
request->setServerURL("client-user.php");
request->addParameter("action",std::string("get-achievements"));
request->addParameter("token", CurrentUser::get()->getToken());
request->addParameter("userid", CurrentUser::get()->getID());
request->addParameter("visitingid", m_id);
HTTPManager::get()->addRequest(request);
}
void Profile::AchievementsRequest::callback()
{
uint32_t user_id(0);
m_result->get("visitingid", &user_id);
getXMLData()->get("visitingid", &user_id);
if( ProfileManager::get()->getProfileByID(user_id) != NULL )
ProfileManager::get()->getProfileByID(user_id)->achievementsCallback(m_result);
ProfileManager::get()->getProfileByID(user_id)
->achievementsCallback(getXMLData());
}
// ============================================================================
@@ -196,20 +197,21 @@ namespace Online{
{
assert(CurrentUser::get()->isRegisteredUser());
FriendsListRequest * request = new FriendsListRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action",std::string("get-friends-list"));
request->setParameter("token", CurrentUser::get()->getToken());
request->setParameter("userid", CurrentUser::get()->getID());
request->setParameter("visitingid", m_id);
request->setServerURL("client-user.php");
request->addParameter("action",std::string("get-friends-list"));
request->addParameter("token", CurrentUser::get()->getToken());
request->addParameter("userid", CurrentUser::get()->getID());
request->addParameter("visitingid", m_id);
HTTPManager::get()->addRequest(request);
}
void Profile::FriendsListRequest::callback()
{
uint32_t user_id(0);
m_result->get("visitingid", &user_id);
getXMLData()->get("visitingid", &user_id);
if( ProfileManager::get()->getProfileByID(user_id) != NULL )
ProfileManager::get()->getProfileByID(user_id)->friendsListCallback(m_result);
ProfileManager::get()->getProfileByID(user_id)
->friendsListCallback(getXMLData());
}
// ============================================================================

View File

@@ -16,9 +16,10 @@
#include "online/request.hpp"
#include "config/user_config.hpp"
#include "online/http_manager.hpp"
#include "utils/translation.hpp"
#include "utils/constants.hpp"
#include "utils/translation.hpp"
#ifdef WIN32
# include <winsock2.h>
@@ -33,12 +34,15 @@ namespace Online{
class HTTPManager;
// =========================================================================================
// ========================================================================
/**
* Creates a request that can be handled by the HTTPManager
* \param manage_memory whether or not the HTTPManager should take care of deleting the object after all callbacks have been done
* \param priority by what priority should the HTTPManager take care of this request
* \param type indicates whether the request has a special task for the HTTPManager
* Creates a request that can be handled by the HTTPManager
* \param manage_memory whether or not the HTTPManager should take care of
* deleting the object after all callbacks have been done
* \param priority by what priority should the HTTPManager take care of
* this request
* \param type indicates whether the request has a special task for the
* HTTPManager
*/
Request::Request(bool manage_memory, int priority, int type)
: m_type(type), m_manage_memory(manage_memory), m_priority(priority)
@@ -47,67 +51,93 @@ namespace Online{
m_state.setAtomic(S_PREPARING);
} // Request
Request::~Request()
{
}
// ------------------------------------------------------------------------
/** Executes the request. This calles prepareOperation, operation, and
* afterOperation.
*/
void Request::execute()
{
assert(isBusy());
prepareOperation();
operation();
setExecuted();
afterOperation();
}
void Request::afterOperation()
} // execute
// ------------------------------------------------------------------------
/** Executes the request now, i.e. in the main thread and without involving
* the manager thread.. This calles prepareOperation, operation, and
* afterOperation.
*/
void Request::executeNow()
{
}
assert(isPreparing());
setBusy();
execute();
callback();
setDone();
} // executeNow
// =========================================================================================
/**
* Creates a HTTP(S) request that will have a raw string as result. (Can ofcourse be used if the result doesn't matter.)
* \param manage_memory whether or not the HTTPManager should take care of deleting the object after all callbacks have been done
* \param priority by what priority should the HTTPManager take care of this request
// ========================================================================
/** Creates a HTTP(S) request that will have a raw string as result. (Can
* of course be used if the result doesn't matter.)
* \param manage_memory whether or not the HTTPManager should take care of
* deleting the object after all callbacks have been done.
* \param priority by what priority should the HTTPManager take care of
* this request.
*/
HTTPRequest::HTTPRequest(bool manage_memory, int priority)
: Request(manage_memory, priority, 0)
: Request(manage_memory, priority, 0)
{
m_url = "";
m_parameters = new Parameters();
m_url = "";
m_string_buffer = "";
m_parameters = new Parameters();
m_progress.setAtomic(0);
}
} // HTTPRequest
// ------------------------------------------------------------------------
HTTPRequest::~HTTPRequest()
{
delete m_parameters;
}
} // ~HTTPRequest
/**
* Checks the request if it has enough (correct) information to be executed (and thus allowed to add to the queue)
// ------------------------------------------------------------------------
/** A handy shortcut that appends the given path to the URL of the server.
* \param path The path to add to the server.
*/
void HTTPRequest::setServerURL(const std::string& path)
{
setURL((std::string)UserConfigParams::m_server_multiplayer+path);
} // setServerURL
// ------------------------------------------------------------------------
/** Checks the request if it has enough (correct) information to be
* executed (and thus allowed to add to the queue).
*/
bool HTTPRequest::isAllowedToAdd()
{
if (!Request::isAllowedToAdd() || m_url.size() < 5 || ( m_url.substr(0, 5) != "http:"))
{
return false;
}
return true;
}
return Request::isAllowedToAdd() && m_url.substr(0, 5) == "http:";
} // isAllowedToAdd
// ------------------------------------------------------------------------
/** Sets up the curl data structures.
*/
void HTTPRequest::prepareOperation()
{
m_curl_session = curl_easy_init();
if(!m_curl_session)
{
Log::error("HTTPRequest::prepareOperation", "LibCurl session not initialized.");
Log::error("HTTPRequest::prepareOperation",
"LibCurl session not initialized.");
return;
}
curl_easy_setopt(m_curl_session, CURLOPT_URL, m_url.c_str());
curl_easy_setopt(m_curl_session, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(m_curl_session, CURLOPT_WRITEFUNCTION, &HTTPRequest::WriteCallback);
curl_easy_setopt(m_curl_session, CURLOPT_WRITEFUNCTION,
&HTTPRequest::writeCallback);
curl_easy_setopt(m_curl_session, CURLOPT_NOPROGRESS, 0);
curl_easy_setopt(m_curl_session, CURLOPT_PROGRESSDATA, this);
curl_easy_setopt(m_curl_session, CURLOPT_PROGRESSFUNCTION, &HTTPRequest::progressDownload);
curl_easy_setopt(m_curl_session, CURLOPT_PROGRESSFUNCTION,
&HTTPRequest::progressDownload);
curl_easy_setopt(m_curl_session, CURLOPT_CONNECTTIMEOUT, 20);
curl_easy_setopt(m_curl_session, CURLOPT_LOW_SPEED_LIMIT, 10);
curl_easy_setopt(m_curl_session, CURLOPT_LOW_SPEED_TIME, 20);
@@ -115,12 +145,16 @@ namespace Online{
struct curl_slist *chunk = NULL;
chunk = curl_slist_append(chunk, "Host: api.stkaddons.net");
curl_easy_setopt(m_curl_session, CURLOPT_HTTPHEADER, chunk);
curl_easy_setopt(m_curl_session, CURLOPT_CAINFO, (file_manager->getAsset("web.tuxfamily.org.pem")).c_str());
curl_easy_setopt(m_curl_session, CURLOPT_CAINFO,
(file_manager->getAsset("web.tuxfamily.org.pem")).c_str());
curl_easy_setopt(m_curl_session, CURLOPT_SSL_VERIFYPEER, 0L);
//curl_easy_setopt(m_curl_session, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(m_curl_session, CURLOPT_WRITEDATA, &m_string_buffer);
}
} // prepareOperation
// ------------------------------------------------------------------------
/** The actual curl download happens here.
*/
void HTTPRequest::operation()
{
if(!m_curl_session)
@@ -131,16 +165,22 @@ namespace Online{
{
if(iter != m_parameters->begin())
postString.append("&");
char * escaped = curl_easy_escape(m_curl_session , iter->first.c_str(), iter->first.size());
char* escaped = curl_easy_escape(m_curl_session ,
iter->first.c_str(),
iter->first.size());
postString.append(escaped);
curl_free(escaped);
postString.append("=");
escaped = curl_easy_escape(m_curl_session , iter->second.c_str(), iter->second.size());
escaped = curl_easy_escape(m_curl_session,
iter->second.c_str(),
iter->second.size());
postString.append(escaped);
curl_free(escaped);
}
Log::info( "HTTPRequest::operation", "Sending : %s", postString.c_str());
curl_easy_setopt(m_curl_session, CURLOPT_POSTFIELDS, postString.c_str());
Log::info("HTTPRequest::operation", "Sending : %s",
postString.c_str());
curl_easy_setopt(m_curl_session, CURLOPT_POSTFIELDS,
postString.c_str());
std::string uagent( std::string("SuperTuxKart/") + STK_VERSION );
#ifdef WIN32
uagent += (std::string)" (Windows)";
@@ -156,8 +196,14 @@ namespace Online{
curl_easy_setopt(m_curl_session, CURLOPT_USERAGENT, uagent.c_str());
m_curl_code = curl_easy_perform(m_curl_session);
}
Request::operation();
} // operation
// ------------------------------------------------------------------------
/** Cleanup once the download is finished. The value of progress is
* guaranteed to be >=0 and <1 while the download is in progress, and
* will only be set to 1 on a successfull finish here.
*/
void HTTPRequest::afterOperation()
{
if(m_curl_code == CURLE_OK)
@@ -166,26 +212,27 @@ namespace Online{
setProgress(-1.0f);
Request::afterOperation();
curl_easy_cleanup(m_curl_session);
}
} // afterOperation
size_t HTTPRequest::WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
// ------------------------------------------------------------------------
/** Callback from curl. This stores the data received by curl in the
* buffer of this request.
* \param content Pointer to the data received by curl.
* \param size Size of one block.
* \param nmemb Number of blocks received.
* \param userp Pointer to the user buffer.
*/
size_t HTTPRequest::writeCallback(void *contents, size_t size,
size_t nmemb, void *userp)
{
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
/**
* \pre request has to be done
* \return get the result string from the request reply
*/
const std::string & HTTPRequest::getResult() const
{
assert(isDone());
return m_string_buffer;
}
} // writeCallback
// ----------------------------------------------------------------------------
/** Callback function from curl: inform about progress.
/** Callback function from curl: inform about progress. It makes sure that
* the value reported by getProgress () is <1 while the download is still
* in progress.
* \param clientp
* \param download_total Total size of data to download.
* \param download_now How much has been downloaded so far.
@@ -219,7 +266,7 @@ namespace Online{
}
else
{
// Don't set progress to 1.0f; this is done in loadFileInternal
// Don't set progress to 1.0f; this is done in afterOperation()
// after checking curls return code!
f= download_total==0 ? 0 : 0.99f;
}
@@ -227,84 +274,51 @@ namespace Online{
return 0;
} // progressDownload
// =========================================================================================
/**
* Creates a HTTP(S) request that will automatically parse the answer into a XML structure
* \param manage_memory whether or not the HTTPManager should take care of deleting the object after all callbacks have been done
* \param priority by what priority should the HTTPManager take care of this request
// ========================================================================
/** Creates a HTTP(S) request that will automatically parse the answer into
* a XML structure.
* \param manage_memory whether or not the HTTPManager should take care of
* deleting the object after all callbacks have been done.
* \param priority by what priority should the HTTPManager take care of
* this request.
*/
XMLRequest::XMLRequest(bool manage_memory, int priority)
: HTTPRequest(manage_memory, priority)
: HTTPRequest(manage_memory, priority)
{
m_string_buffer = "";
m_info = "";
m_success = false;
m_result = NULL;
}
m_info = "";
m_success = false;
m_xml_data = NULL;
} // XMLRequest
// ------------------------------------------------------------------------
/** Cleans up the XML tree. */
XMLRequest::~XMLRequest()
{
delete m_result;
}
void XMLRequest::prepareOperation()
{
HTTPRequest::prepareOperation();
}
void XMLRequest::operation()
{
HTTPRequest::operation();
m_result = file_manager->createXMLTreeFromString(m_string_buffer);
}
delete m_xml_data;
} // ~XMLRequest
// ------------------------------------------------------------------------
/** On a successful download converts the string into an XML tree.
*/
void XMLRequest::afterOperation()
{
if(m_curl_code != CURLE_OK)
Log::error( "XMLRequest::afterOperation", "curl_easy_perform() failed: %s", curl_easy_strerror(m_curl_code));
bool success = false;
m_xml_data = file_manager->createXMLTreeFromString(getData());
if(getResult() != CURLE_OK)
Log::error("XMLRequest::afterOperation",
"curl_easy_perform() failed: %s",
curl_easy_strerror(getResult()));
m_success = false;
std::string rec_success;
if(m_result->get("success", &rec_success))
if(m_xml_data->get("success", &rec_success))
{
if (rec_success =="yes")
success = true;
m_result->get("info", &m_info);
m_success = rec_success =="yes";
m_xml_data->get("info", &m_info);
}
else
m_info = _("Unable to connect to the server. Check your internet connection or try again later.");
m_success = success;
m_info = _("Unable to connect to the server. Check your internet "
"connection or try again later.");
HTTPRequest::afterOperation();
}
} // afterOperation
/**
* \pre request has to be done
* \return get the complete result from the request reply
*/
const XMLNode * XMLRequest::getResult() const
{
assert(isDone());
return m_result;
}
/**
* \pre request has to be done
* \return get the info from the request reply
*/
const irr::core::stringw & XMLRequest::getInfo() const
{
assert(isDone());
return m_info;
}
/**
* \pre request has to be done
* \return whether or not the request was a success
*/
bool XMLRequest::isSuccess() const
{
assert(isDone());
return m_success;
}
} // namespace Online

View File

@@ -1,5 +1,5 @@
// SuperTuxKart - a fun racing game with go-kart
// Copyright (C) 2011 Joerg Henrichs
// Copyright (C) 2011-2013 Joerg Henrichs
// 2013 Glenn De Jonghe
//
// This program is free software; you can redistribute it and/or
@@ -33,16 +33,34 @@
namespace Online{
/**
* Stores a request for the HTTP Manager. They will be sorted by priorities.
* \ingroup online
*/
/** Stores a request for the HTTP Manager. They will be sorted by
* prioritiy. Requests have four different states they can be in, and
* this state determines which thread can access it. This allows
* the use of threading without adding more synchronisation overhead
* and code to the main thread. The states are:
* - Preparing\n The request is created, and parameter are set.
* Only the main thread can access this object.
* - Busy\n The request is put into the http_manager queue. It remains
* in this states till its operation is finished. No more changes
* to this object by the main thread are allowed, only the manager
* thread can change it now.
* - Executed\n The request was executed (its operation called and
* finished), but callbacks still need to be done by the manager
* thread (main reason for this state is to have asserts in
* function accessing data).
* - Done\n All callbacks are done (they will be executed by the main
* thread), the request was moved from the manager's request queue
* to its finished queue, executed its callbacks and was removed
* from the queue. The manager thread will not access this object
* anymore, and the main thread is now able to access the request
* object again.
*
* \ingroup online
*/
class Request
{
private:
/** Type of the request
* Has 0 as default value.
* */
/** Type of the request. Has 0 as default value. */
const int m_type;
/** True if the memory for this Request should be managed by
* http connector (i.e. this object is freed once the request
@@ -53,10 +71,26 @@ namespace Online{
important this request is. */
const int m_priority;
/** The different state of the requst:
* - S_PREPARING:\n The request is created and can be configured, it
* is not yet started.
* - S_BUSY:\n The request is added to the execution queue of the
* http_manager (and potentially executing). This implies that
* now only the http_manager thread should access the requests's
* data structures.
* - S_EXECUTED:\n The request was executed, but was not yet marked
* as finished in the http_manager. This importantly indicates
* that the main thread should not yet access this request,
* since the http thread is still executing it.
* - S_DONE:\n The request is finished, and it is marked as
* finished in the http_manager. This implies that the main
* stk thread can access its data safely now.
*/
enum State
{
S_PREPARING,
S_BUSY,
S_EXECUTED,
S_DONE
};
@@ -64,12 +98,20 @@ namespace Online{
/** Cancel this request if it is active. */
Synchronised<bool> m_cancel;
/** Set to though if the reply of the request is in and callbacks are executed */
/** Set to though if the reply of the request is in and callbacks are
* executed */
Synchronised<State> m_state;
virtual void prepareOperation() {}
// --------------------------------------------------------------------
/** The actual operation to be executed. Empty as default, which
* allows to create a 'quit' request without any additional code. */
virtual void operation() {}
virtual void afterOperation();
// --------------------------------------------------------------------
/** Virtual function to be called before an operation. */
virtual void prepareOperation() {}
// --------------------------------------------------------------------
/** Virtual function to be called after an operation. */
virtual void afterOperation() {}
public:
enum RequestType
@@ -77,47 +119,76 @@ namespace Online{
RT_QUIT = 1
};
Request(bool manage_memory, int priority, int type);
virtual ~Request();
void execute();
int getType() const { return m_type; }
// ------------------------------------------------------------------------
Request(bool manage_memory, int priority, int type);
virtual ~Request() {}
void execute();
void executeNow();
// --------------------------------------------------------------------
/** Executed when a request has finished. */
virtual void callback() {}
// --------------------------------------------------------------------
/** Returns the type of the request. */
int getType() const { return m_type; }
// --------------------------------------------------------------------
/** Returns if the memory for this object should be managed by
* by network_http (i.e. freed once the request is handled). */
bool manageMemory() const { return m_manage_memory; }
// ------------------------------------------------------------------------
bool manageMemory() const { return m_manage_memory; }
// --------------------------------------------------------------------
/** Returns the priority of this request. */
int getPriority() const { return m_priority; }
// ------------------------------------------------------------------------
int getPriority() const { return m_priority; }
// --------------------------------------------------------------------
/** Signals that this request should be canceled. */
void cancel() { m_cancel.setAtomic(true); }
// ------------------------------------------------------------------------
void cancel() { m_cancel.setAtomic(true); }
// --------------------------------------------------------------------
/** Returns if this request is to be canceled. */
bool isCancelled() const { return m_cancel.getAtomic(); }
// ------------------------------------------------------------------------
/** Returns if this request is done. */
bool isDone() const { return m_state.getAtomic() == S_DONE; }
// ------------------------------------------------------------------------
bool isCancelled() const { return m_cancel.getAtomic(); }
// --------------------------------------------------------------------
/** Sets the request state to busy. */
void setBusy()
{
assert(m_state.getAtomic()==S_PREPARING);
m_state.setAtomic(S_BUSY);
} // setBusy
// --------------------------------------------------------------------
/** Sets the request to be completed. */
void setExecuted()
{
assert(m_state.getAtomic()==S_BUSY);
m_state.setAtomic(S_EXECUTED);
} // setExecuted
// --------------------------------------------------------------------
/** Should only be called by the manager */
void setDone() { m_state.setAtomic(S_DONE); }
// ------------------------------------------------------------------------
void setDone()
{
assert(m_state.getAtomic()==S_EXECUTED);
m_state.setAtomic(S_DONE);
} // setDone
// --------------------------------------------------------------------
/** Returns if this request is done. */
bool isDone() const { return m_state.getAtomic() == S_DONE; }
// --------------------------------------------------------------------
/** Returns if this request is being prepared. */
bool isPreparing() const { return m_state.getAtomic() == S_PREPARING; }
// ------------------------------------------------------------------------
bool isPreparing() const { return m_state.getAtomic() == S_PREPARING; }
// --------------------------------------------------------------------
/** Returns if this request is busy. */
bool isBusy() const { return m_state.getAtomic() == S_BUSY; }
// ------------------------------------------------------------------------
/** Sets the request stqte to busy. */
void setBusy() { m_state.setAtomic(S_BUSY); }
// ------------------------------------------------------------------------
/** Virtual method to check if a request has initialized all needed members to a valid value. */
bool isBusy() const { return m_state.getAtomic() == S_BUSY; }
// --------------------------------------------------------------------
/** Checks if the request has completed or done (i.e. callbacks were
* executed).
*/
bool hasBeenExecuted() const
{
State s = m_state.getAtomic();
return s==S_EXECUTED || s==S_DONE;
} // hasBeenExecuted
// --------------------------------------------------------------------
/** Virtual method to check if a request has initialized all needed
* members to a valid value. */
virtual bool isAllowedToAdd() const { return isPreparing(); }
/** Executed when a request has finished. */
virtual void callback() {}
/** This class is used by the priority queue to sort requests by priority.
// ====================================================================
/** This class is used by the priority queue to sort requests by
* priority.
*/
class Compare
{
@@ -133,96 +204,169 @@ namespace Online{
// ========================================================================
/** A http request.
*/
class HTTPRequest : public Request
{
protected :
typedef std::map<std::string, std::string> Parameters;
private:
typedef std::map<std::string, std::string> Parameters;
/** The progress indicator. 0 untill it is started and the first
* packet is downloaded. At the end either -1 (error) or 1
* (everything ok) at the end. */
Synchronised<float> m_progress;
std::string m_url;
* packet is downloaded. Guaranteed to be <1 while the download
* is in progress, it will be set to either -1 (error) or 1
* (everything ok) at the end. */
Synchronised<float> m_progress;
/** The url to download. */
std::string m_url;
/** The POST parameters that will be send with the request. */
Parameters * m_parameters;
CURL * m_curl_session;
CURLcode m_curl_code;
std::string m_string_buffer;
Parameters *m_parameters;
virtual void prepareOperation() OVERRIDE;
virtual void operation() OVERRIDE;
virtual void afterOperation() OVERRIDE;
/** Pointer to the curl data structure for this request. */
CURL *m_curl_session;
/** curl return code. */
CURLcode m_curl_code;
static int progressDownload( void *clientp,
double dltotal,
double dlnow,
double ultotal,
double ulnow);
/** String to store the received data in. */
std::string m_string_buffer;
static size_t WriteCallback( void *contents,
size_t size,
size_t nmemb,
void *userp);
protected:
virtual void prepareOperation() OVERRIDE;
virtual void operation() OVERRIDE;
virtual void afterOperation() OVERRIDE;
static int progressDownload(void *clientp, double dltotal,
double dlnow, double ultotal,
double ulnow);
static size_t writeCallback(void *contents, size_t size,
size_t nmemb, void *userp);
public :
HTTPRequest(bool manage_memory = false, int priority = 1);
virtual ~HTTPRequest();
HTTPRequest(bool manage_memory = false,
int priority = 1);
virtual ~HTTPRequest();
virtual bool isAllowedToAdd() OVERRIDE;
void setServerURL(const std::string& url);
// ------------------------------------------------------------------------
/** Returns the curl error status of the request.
*/
CURLcode getResult() const { return m_curl_code; }
// ------------------------------------------------------------------------
/** Returns the downloaded string.
* \pre request has to be done
* \return get the result string from the request reply
*/
const std::string & HTTPRequest::getData() const
{
assert(hasBeenExecuted());
return m_string_buffer;
} // getData
void setParameter(const std::string & name, const std::string &value){
// --------------------------------------------------------------------
/** Sets a parameter to 'value' (std::string).
*/
void addParameter(const std::string & name, const std::string &value)
{
assert(isPreparing());
(*m_parameters)[name] = value;
};
void setParameter(const std::string & name, const irr::core::stringw &value){
}; // addParameter
// --------------------------------------------------------------------
/** Sets a parameter to 'value' (stringw).
*/
void addParameter(const std::string & name,
const irr::core::stringw &value)
{
assert(isPreparing());
(*m_parameters)[name] = irr::core::stringc(value.c_str()).c_str();
}
} // addParameter
// --------------------------------------------------------------------
/** Sets a parameter to 'value' (arbitrary types).
*/
template <typename T>
void setParameter(const std::string & name, const T& value){
void addParameter(const std::string & name, const T& value){
assert(isPreparing());
(*m_parameters)[name] = StringUtils::toString(value);
}
const std::string & getResult() const;
} // addParameter
// --------------------------------------------------------------------
/** Returns the current progress. */
float getProgress() const { return m_progress.getAtomic(); }
float getProgress() const { return m_progress.getAtomic(); }
// --------------------------------------------------------------------
/** Sets the current progress. */
void setProgress(float f) { m_progress.setAtomic(f); }
void setProgress(float f) { m_progress.setAtomic(f); }
// --------------------------------------------------------------------
const std::string & getURL() const { assert(isBusy()); return m_url;}
// --------------------------------------------------------------------
/** Sets the URL for this request. */
void setURL(const std::string & url)
{
assert(isPreparing());
m_url = url;
} // setURL
const std::string & getURL() { assert(isBusy()); return m_url;}
void setURL(const std::string & url) { assert(isPreparing()); m_url = url;}
virtual bool isAllowedToAdd() OVERRIDE;
};
}; // class HTTPRequest
// ========================================================================
/** A http request expecting a xml return value.
*/
class XMLRequest : public HTTPRequest
{
protected :
XMLNode * m_result;
irr::core::stringw m_info;
bool m_success;
private:
/** On a successful download contains the converted XML tree. */
XMLNode *m_xml_data;
virtual void prepareOperation() OVERRIDE;
virtual void operation() OVERRIDE;
virtual void afterOperation() OVERRIDE;
/** Additional info contained the downloaded data (or an error
* message if a problem occurred). */
irr::core::stringw m_info;
/** True if the request was successful executed on the server. */
bool m_success;
protected:
virtual void afterOperation() OVERRIDE;
public :
XMLRequest(bool manage_memory = false, int priority = 1);
XMLRequest(bool manage_memory = false, int priority = 1);
virtual ~XMLRequest();
const XMLNode * getResult() const;
const irr::core::stringw & getInfo() const;
bool isSuccess() const;
// ------------------------------------------------------------------------
/** Get the downloaded XML tree.
* \pre request has to be executed.
* \return get the complete result from the request reply.
*/
const XMLNode * XMLRequest::getXMLData() const
{
assert(hasBeenExecuted());
return m_xml_data;
} // getXMLData
// ------------------------------------------------------------------------
/** Returns the additional information (or error message) contained in
* a finished request.
* \pre request had to be executed.
* \return get the info from the request reply
*/
const irr::core::stringw & XMLRequest::getInfo() const
{
assert(hasBeenExecuted());
return m_info;
} // getInfo
// --------------------------------------------------------------------
/** Returns whether the request was successfully executed on the server.
* \pre request had to be executed.
* \return whether or not the request was a success. */
bool isSuccess() const
{
assert(hasBeenExecuted());
return m_success;
} // isSuccess
}; // class XMLRequest
};
} //namespace Online
#endif

View File

@@ -75,8 +75,8 @@ namespace Online{
if(StkTime::getRealTime() - m_last_load_time.getAtomic() > SERVER_REFRESH_INTERVAL)
{
request = new RefreshRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action",std::string("get_server_list"));
request->setServerURL("client-user.php");
request->addParameter("action",std::string("get_server_list"));
if (request_now)
HTTPManager::get()->addRequest(request);
}
@@ -100,7 +100,7 @@ namespace Online{
void ServersManager::RefreshRequest::callback()
{
ServersManager::get()->refresh(m_success, m_result);
ServersManager::get()->refresh(isSuccess(), getXMLData());
}
// ============================================================================

View File

@@ -115,11 +115,11 @@ void VoteDialog::onUpdate(float dt)
{
m_info_widget->setDefaultColor();
std::string voted("");
m_fetch_vote_request->getResult()->get("voted", &voted);
m_fetch_vote_request->getXMLData()->get("voted", &voted);
if(voted == "yes")
{
float rating;
m_fetch_vote_request->getResult()->get("rating", &rating);
m_fetch_vote_request->getXMLData()->get("rating", &rating);
m_rating_widget->setRating(rating);
m_info_widget->setText(_("You can adapt your previous rating by clicking the stars beneath."), false);
}

View File

@@ -221,7 +221,7 @@ void OnlineScreen::eventCallback(Widget* widget, const std::string& name, const
Online::ServersManager::RefreshRequest* request = ServersManager::get()->refreshRequest(false);
if (request != NULL) // consider request done
{
Online::HTTPManager::get()->synchronousRequest(request);
request->executeNow();
delete request;
}
else
@@ -235,7 +235,7 @@ void OnlineScreen::eventCallback(Widget* widget, const std::string& name, const
Online::CurrentUser::ServerJoinRequest* request2 = Online::CurrentUser::get()->requestServerJoin( server->getServerId(), false);
if (request2)
{
Online::HTTPManager::get()->synchronousRequest(request2);
request2->executeNow();
if (request2->isSuccess())
{
delete request2;

View File

@@ -182,7 +182,7 @@ void OnlineUserSearch::onUpdate(float dt, irr::video::IVideoDriver*)
{
if(m_search_request->isSuccess())
{
parseResult(m_search_request->getResult());
parseResult(m_search_request->getXMLData());
showList();
}
else