Turn RequestBroker::RetrieveAvatar into a request derived from Download

Also add http namespace because classes clashed a lot.
This commit is contained in:
Tamás Bálint Misius 2019-03-07 00:06:07 +01:00 committed by jacob1
parent 8b5cf394e0
commit 53f2018c7e
19 changed files with 203 additions and 123 deletions

View File

@ -0,0 +1,11 @@
#include "AvatarRequest.h"
#include "Config.h"
namespace http
{
AvatarRequest::AvatarRequest(ByteString username, int width, int height) :
ImageRequest(ByteString::Build("http://" STATICSERVER "/avatars/", username, ".pti"), width, height)
{
}
}

View File

@ -0,0 +1,19 @@
#ifndef AVATARREQUEST2_H
#define AVATARREQUEST2_H
#include "ImageRequest.h"
#include "common/String.h"
#include <memory>
namespace http
{
class AvatarRequest : public ImageRequest
{
public:
AvatarRequest(ByteString username, int width, int height);
};
}
#endif // AVATARREQUEST2_H

View File

@ -135,7 +135,7 @@ void Client::Initialise(ByteString proxyString)
stampsLib.close(); stampsLib.close();
//Begin version check //Begin version check
versionCheckRequest = new Download("http://" SERVER "/Startup.json"); versionCheckRequest = new http::Download("http://" SERVER "/Startup.json");
if (authUser.UserID) if (authUser.UserID)
{ {
@ -145,7 +145,7 @@ void Client::Initialise(ByteString proxyString)
#ifdef UPDATESERVER #ifdef UPDATESERVER
// use an alternate update server // use an alternate update server
alternateVersionCheckRequest = new Download("http://" UPDATESERVER "/Startup.json"); alternateVersionCheckRequest = new http::Download("http://" UPDATESERVER "/Startup.json");
usingAltUpdateServer = true; usingAltUpdateServer = true;
if (authUser.UserID) if (authUser.UserID)
{ {
@ -672,7 +672,7 @@ RequestStatus Client::ParseServerReturn(ByteString &result, int status, bool jso
return RequestOkay; return RequestOkay;
if (status != 200) if (status != 200)
{ {
lastError = String::Build("HTTP Error ", status, ": ", ByteString(Download::StatusText(status)).FromUtf8()); lastError = String::Build("HTTP Error ", status, ": ", ByteString(http::StatusText(status)).FromUtf8());
return RequestFailure; return RequestFailure;
} }
@ -702,7 +702,7 @@ RequestStatus Client::ParseServerReturn(ByteString &result, int status, bool jso
if (!strncmp(result.c_str(), "Error: ", 7)) if (!strncmp(result.c_str(), "Error: ", 7))
{ {
status = ByteString(result.begin() + 7, result.end()).ToNumber<int>(); status = ByteString(result.begin() + 7, result.end()).ToNumber<int>();
lastError = String::Build("HTTP Error ", status, ": ", ByteString(Download::StatusText(status)).FromUtf8()); lastError = String::Build("HTTP Error ", status, ": ", ByteString(http::StatusText(status)).FromUtf8());
return RequestFailure; return RequestFailure;
} }
lastError = "Could not read response: " + ByteString(e.what()).FromUtf8(); lastError = "Could not read response: " + ByteString(e.what()).FromUtf8();
@ -736,14 +736,13 @@ void Client::Tick()
} }
} }
bool Client::CheckUpdate(Download *updateRequest, bool checkSession) bool Client::CheckUpdate(http::Download *updateRequest, bool checkSession)
{ {
//Check status on version check request //Check status on version check request
if (updateRequest->CheckDone()) if (updateRequest->CheckDone())
{ {
int status; int status;
int dataLength; ByteString data = updateRequest->Finish(&status);
ByteString data = updateRequest->Finish(&dataLength, &status);
if (status != 200) if (status != 200)
{ {
@ -962,7 +961,6 @@ RequestStatus Client::UploadSave(SaveInfo & save)
char * gameData = NULL; char * gameData = NULL;
int dataStatus; int dataStatus;
ByteString data; ByteString data;
int dataLength = 0;
ByteString userID = ByteString::Build(authUser.UserID); ByteString userID = ByteString::Build(authUser.UserID);
if (authUser.UserID) if (authUser.UserID)
{ {
@ -989,7 +987,7 @@ RequestStatus Client::UploadSave(SaveInfo & save)
} }
#endif #endif
data = Download::SimpleAuth("http://" SERVER "/Save.api", &dataLength, &dataStatus, userID, authUser.SessionID, { data = http::Download::SimpleAuth("http://" SERVER "/Save.api", &dataStatus, userID, authUser.SessionID, {
{ "Name", save.GetName().ToUtf8() }, { "Name", save.GetName().ToUtf8() },
{ "Description", save.GetDescription().ToUtf8() }, { "Description", save.GetDescription().ToUtf8() },
{ "Data:save.bin", ByteString(gameData, gameData + gameDataLength) }, { "Data:save.bin", ByteString(gameData, gameData + gameDataLength) },
@ -1180,13 +1178,12 @@ RequestStatus Client::ExecVote(int saveID, int direction)
lastError = ""; lastError = "";
int dataStatus; int dataStatus;
ByteString data; ByteString data;
int dataLength = 0;
if (authUser.UserID) if (authUser.UserID)
{ {
ByteString saveIDText = ByteString::Build(saveID); ByteString saveIDText = ByteString::Build(saveID);
ByteString userIDText = ByteString::Build(authUser.UserID); ByteString userIDText = ByteString::Build(authUser.UserID);
data = Download::SimpleAuth("http://" SERVER "/Vote.api", &dataLength, &dataStatus, userIDText, authUser.SessionID, { data = http::Download::SimpleAuth("http://" SERVER "/Vote.api", &dataStatus, userIDText, authUser.SessionID, {
{ "ID", saveIDText }, { "ID", saveIDText },
{ "Action", direction == 1 ? "Up" : "Down" }, { "Action", direction == 1 ? "Up" : "Down" },
}); });
@ -1212,14 +1209,15 @@ unsigned char * Client::GetSaveData(int saveID, int saveDate, int & dataLength)
else else
urlStr = ByteString::Build("http://", STATICSERVER, "/", saveID, ".cps"); urlStr = ByteString::Build("http://", STATICSERVER, "/", saveID, ".cps");
data = Download::Simple(urlStr, &dataLength, &dataStatus); data = http::Download::Simple(urlStr, &dataStatus);
// will always return failure // will always return failure
ParseServerReturn(data, dataStatus, false); ParseServerReturn(data, dataStatus, false);
if (data.size() && dataStatus == 200) if (data.size() && dataStatus == 200)
{ {
unsigned char *data_out = (unsigned char *)malloc(dataLength); unsigned char *data_out = (unsigned char *)malloc(data.size());
std::copy(data_out, data_out + dataLength, data.begin()); std::copy(data_out, data_out + data.size(), data.begin());
dataLength = (int)data.size();
return data_out; return data_out;
} }
return NULL; return NULL;
@ -1336,8 +1334,8 @@ LoginStatus Client::Login(ByteString username, ByteString password, User & user)
totalHash[32] = 0; totalHash[32] = 0;
ByteString data; ByteString data;
int dataStatus, dataLength; int dataStatus;
data = Download::Simple("http://" SERVER "/Login.json", &dataLength, &dataStatus, { data = http::Download::Simple("http://" SERVER "/Login.json", &dataStatus, {
{ "Username", username }, { "Username", username },
{ "Hash", totalHash }, { "Hash", totalHash },
}); });
@ -1392,12 +1390,12 @@ RequestStatus Client::DeleteSave(int saveID)
{ {
lastError = ""; lastError = "";
ByteString data; ByteString data;
int dataStatus, dataLength;
ByteString url = ByteString::Build("http://", SERVER, "/Browse/Delete.json?ID=", saveID, "&Mode=Delete&Key=", authUser.SessionKey); ByteString url = ByteString::Build("http://", SERVER, "/Browse/Delete.json?ID=", saveID, "&Mode=Delete&Key=", authUser.SessionKey);
int dataStatus;
if(authUser.UserID) if(authUser.UserID)
{ {
ByteString userID = ByteString::Build(authUser.UserID); ByteString userID = ByteString::Build(authUser.UserID);
data = Download::SimpleAuth(url, &dataLength, &dataStatus, userID, authUser.SessionID); data = http::Download::SimpleAuth(url, &dataStatus, userID, authUser.SessionID);
} }
else else
{ {
@ -1412,12 +1410,12 @@ RequestStatus Client::AddComment(int saveID, String comment)
{ {
lastError = ""; lastError = "";
ByteString data; ByteString data;
int dataStatus, dataLength; int dataStatus;
ByteString url = ByteString::Build("http://", SERVER, "/Browse/Comments.json?ID=", saveID); ByteString url = ByteString::Build("http://", SERVER, "/Browse/Comments.json?ID=", saveID);
if(authUser.UserID) if(authUser.UserID)
{ {
ByteString userID = ByteString::Build(authUser.UserID); ByteString userID = ByteString::Build(authUser.UserID);
data = Download::SimpleAuth(url, &dataLength, &dataStatus, userID, authUser.SessionID, { data = http::Download::SimpleAuth(url, &dataStatus, userID, authUser.SessionID, {
{ "Comment", comment.ToUtf8() }, { "Comment", comment.ToUtf8() },
}); });
} }
@ -1435,14 +1433,14 @@ RequestStatus Client::FavouriteSave(int saveID, bool favourite)
lastError = ""; lastError = "";
ByteStringBuilder urlStream; ByteStringBuilder urlStream;
ByteString data; ByteString data;
int dataStatus, dataLength; int dataStatus;
urlStream << "http://" << SERVER << "/Browse/Favourite.json?ID=" << saveID << "&Key=" << authUser.SessionKey; urlStream << "http://" << SERVER << "/Browse/Favourite.json?ID=" << saveID << "&Key=" << authUser.SessionKey;
if(!favourite) if(!favourite)
urlStream << "&Mode=Remove"; urlStream << "&Mode=Remove";
if(authUser.UserID) if(authUser.UserID)
{ {
ByteString userID = ByteString::Build(authUser.UserID); ByteString userID = ByteString::Build(authUser.UserID);
data = Download::SimpleAuth(urlStream.Build(), &dataLength, &dataStatus, userID, authUser.SessionID); data = http::Download::SimpleAuth(urlStream.Build(), &dataStatus, userID, authUser.SessionID);
} }
else else
{ {
@ -1457,12 +1455,12 @@ RequestStatus Client::ReportSave(int saveID, String message)
{ {
lastError = ""; lastError = "";
ByteString data; ByteString data;
int dataStatus, dataLength; int dataStatus;
ByteString url = ByteString::Build("http://", SERVER, "/Browse/Report.json?ID=", saveID, "&Key=", authUser.SessionKey); ByteString url = ByteString::Build("http://", SERVER, "/Browse/Report.json?ID=", saveID, "&Key=", authUser.SessionKey);
if(authUser.UserID) if(authUser.UserID)
{ {
ByteString userID = ByteString::Build(authUser.UserID); ByteString userID = ByteString::Build(authUser.UserID);
data = Download::SimpleAuth(url, &dataLength, &dataStatus, userID, authUser.SessionID, { data = http::Download::SimpleAuth(url, &dataStatus, userID, authUser.SessionID, {
{ "Reason", message.ToUtf8() }, { "Reason", message.ToUtf8() },
}); });
} }
@ -1479,12 +1477,12 @@ RequestStatus Client::UnpublishSave(int saveID)
{ {
lastError = ""; lastError = "";
ByteString data; ByteString data;
int dataStatus, dataLength; int dataStatus;
ByteString url = ByteString::Build("http://", SERVER, "/Browse/Delete.json?ID=", saveID, "&Mode=Unpublish&Key=", authUser.SessionKey); ByteString url = ByteString::Build("http://", SERVER, "/Browse/Delete.json?ID=", saveID, "&Mode=Unpublish&Key=", authUser.SessionKey);
if(authUser.UserID) if(authUser.UserID)
{ {
ByteString userID = ByteString::Build(authUser.UserID); ByteString userID = ByteString::Build(authUser.UserID);
data = Download::SimpleAuth(url, &dataLength, &dataStatus, userID, authUser.SessionID); data = http::Download::SimpleAuth(url, &dataStatus, userID, authUser.SessionID);
} }
else else
{ {
@ -1504,7 +1502,7 @@ RequestStatus Client::PublishSave(int saveID)
if (authUser.UserID) if (authUser.UserID)
{ {
ByteString userID = ByteString::Build(authUser.UserID); ByteString userID = ByteString::Build(authUser.UserID);
data = Download::SimpleAuth(url, nullptr, &dataStatus, userID, authUser.SessionID, { data = http::Download::SimpleAuth(url, &dataStatus, userID, authUser.SessionID, {
{ "ActionPublish", "bagels" }, { "ActionPublish", "bagels" },
}); });
} }
@ -1527,16 +1525,16 @@ SaveInfo * Client::GetSave(int saveID, int saveDate)
urlStream << "&Date=" << saveDate; urlStream << "&Date=" << saveDate;
} }
ByteString data; ByteString data;
int dataStatus, dataLength; int dataStatus;
if(authUser.UserID) if(authUser.UserID)
{ {
ByteString userID = ByteString::Build(authUser.UserID); ByteString userID = ByteString::Build(authUser.UserID);
data = Download::SimpleAuth(urlStream.Build(), &dataLength, &dataStatus, userID, authUser.SessionID); data = http::Download::SimpleAuth(urlStream.Build(), &dataStatus, userID, authUser.SessionID);
} }
else else
{ {
data = Download::Simple(urlStream.Build(), &dataLength, &dataStatus); data = http::Download::Simple(urlStream.Build(), &dataStatus);
} }
if(dataStatus == 200 && data.size()) if(dataStatus == 200 && data.size())
{ {
@ -1583,7 +1581,7 @@ SaveInfo * Client::GetSave(int saveID, int saveDate)
} }
else else
{ {
lastError = ByteString(Download::StatusText(dataStatus)).FromUtf8(); lastError = ByteString(http::StatusText(dataStatus)).FromUtf8();
} }
return NULL; return NULL;
} }
@ -1699,7 +1697,7 @@ std::vector<std::pair<ByteString, int> > * Client::GetTags(int start, int count,
std::vector<std::pair<ByteString, int> > * tagArray = new std::vector<std::pair<ByteString, int> >(); std::vector<std::pair<ByteString, int> > * tagArray = new std::vector<std::pair<ByteString, int> >();
ByteStringBuilder urlStream; ByteStringBuilder urlStream;
ByteString data; ByteString data;
int dataStatus, dataLength; int dataStatus;
urlStream << "http://" << SERVER << "/Browse/Tags.json?Start=" << start << "&Count=" << count; urlStream << "http://" << SERVER << "/Browse/Tags.json?Start=" << start << "&Count=" << count;
if(query.length()) if(query.length())
{ {
@ -1708,7 +1706,7 @@ std::vector<std::pair<ByteString, int> > * Client::GetTags(int start, int count,
urlStream << format::URLEncode(query.ToUtf8()); urlStream << format::URLEncode(query.ToUtf8());
} }
data = Download::Simple(urlStream.Build(), &dataLength, &dataStatus); data = http::Download::Simple(urlStream.Build(), &dataStatus);
if(dataStatus == 200 && data.size()) if(dataStatus == 200 && data.size())
{ {
try try
@ -1733,7 +1731,7 @@ std::vector<std::pair<ByteString, int> > * Client::GetTags(int start, int count,
} }
else else
{ {
lastError = ByteString(Download::StatusText(dataStatus)).FromUtf8(); lastError = ByteString(http::StatusText(dataStatus)).FromUtf8();
} }
return tagArray; return tagArray;
} }
@ -1745,7 +1743,7 @@ std::vector<SaveInfo*> * Client::SearchSaves(int start, int count, String query,
std::vector<SaveInfo*> * saveArray = new std::vector<SaveInfo*>(); std::vector<SaveInfo*> * saveArray = new std::vector<SaveInfo*>();
ByteStringBuilder urlStream; ByteStringBuilder urlStream;
ByteString data; ByteString data;
int dataStatus, dataLength; int dataStatus;
urlStream << "http://" << SERVER << "/Browse.json?Start=" << start << "&Count=" << count; urlStream << "http://" << SERVER << "/Browse.json?Start=" << start << "&Count=" << count;
if(query.length() || sort.length()) if(query.length() || sort.length())
{ {
@ -1766,11 +1764,11 @@ std::vector<SaveInfo*> * Client::SearchSaves(int start, int count, String query,
if(authUser.UserID) if(authUser.UserID)
{ {
ByteString userID = ByteString::Build(authUser.UserID); ByteString userID = ByteString::Build(authUser.UserID);
data = Download::SimpleAuth(urlStream.Build(), &dataLength, &dataStatus, userID, authUser.SessionID); data = http::Download::SimpleAuth(urlStream.Build(), &dataStatus, userID, authUser.SessionID);
} }
else else
{ {
data = Download::Simple(urlStream.Build(), &dataLength, &dataStatus); data = http::Download::Simple(urlStream.Build(), &dataStatus);
} }
ParseServerReturn(data, dataStatus, true); ParseServerReturn(data, dataStatus, true);
if (dataStatus == 200 && data.size()) if (dataStatus == 200 && data.size())
@ -1813,12 +1811,12 @@ std::list<ByteString> * Client::RemoveTag(int saveID, ByteString tag)
lastError = ""; lastError = "";
std::list<ByteString> * tags = NULL; std::list<ByteString> * tags = NULL;
ByteString data; ByteString data;
int dataStatus, dataLength; int dataStatus;
ByteString url = ByteString::Build("http://", SERVER, "/Browse/EditTag.json?Op=delete&ID=", saveID, "&Tag=", tag, "&Key=", authUser.SessionKey); ByteString url = ByteString::Build("http://", SERVER, "/Browse/EditTag.json?Op=delete&ID=", saveID, "&Tag=", tag, "&Key=", authUser.SessionKey);
if(authUser.UserID) if(authUser.UserID)
{ {
ByteString userID = ByteString::Build(authUser.UserID); ByteString userID = ByteString::Build(authUser.UserID);
data = Download::SimpleAuth(url, &dataLength, &dataStatus, userID, authUser.SessionID); data = http::Download::SimpleAuth(url, &dataStatus, userID, authUser.SessionID);
} }
else else
{ {
@ -1852,12 +1850,12 @@ std::list<ByteString> * Client::AddTag(int saveID, ByteString tag)
lastError = ""; lastError = "";
std::list<ByteString> * tags = NULL; std::list<ByteString> * tags = NULL;
ByteString data; ByteString data;
int dataStatus, dataLength; int dataStatus;
ByteString url = ByteString::Build("http://", SERVER, "/Browse/EditTag.json?Op=add&ID=", saveID, "&Tag=", tag, "&Key=", authUser.SessionKey); ByteString url = ByteString::Build("http://", SERVER, "/Browse/EditTag.json?Op=add&ID=", saveID, "&Tag=", tag, "&Key=", authUser.SessionKey);
if(authUser.UserID) if(authUser.UserID)
{ {
ByteString userID = ByteString::Build(authUser.UserID); ByteString userID = ByteString::Build(authUser.UserID);
data = Download::SimpleAuth(url, &dataLength, &dataStatus, userID, authUser.SessionID); data = http::Download::SimpleAuth(url, &dataStatus, userID, authUser.SessionID);
} }
else else
{ {

View File

@ -48,14 +48,17 @@ public:
class RequestListener; class RequestListener;
class ClientListener; class ClientListener;
class Download; namespace http
{
class Download;
}
class Client: public Singleton<Client> { class Client: public Singleton<Client> {
private: private:
String messageOfTheDay; String messageOfTheDay;
std::vector<std::pair<String, ByteString> > serverNotifications; std::vector<std::pair<String, ByteString> > serverNotifications;
Download *versionCheckRequest; http::Download *versionCheckRequest;
Download *alternateVersionCheckRequest; http::Download *alternateVersionCheckRequest;
bool usingAltUpdateServer; bool usingAltUpdateServer;
bool updateAvailable; bool updateAvailable;
UpdateInfo updateInfo; UpdateInfo updateInfo;
@ -175,7 +178,7 @@ public:
} }
RequestStatus ParseServerReturn(ByteString &result, int status, bool json); RequestStatus ParseServerReturn(ByteString &result, int status, bool json);
void Tick(); void Tick();
bool CheckUpdate(Download *updateRequest, bool checkSession); bool CheckUpdate(http::Download *updateRequest, bool checkSession);
void Shutdown(); void Shutdown();
// preferences functions // preferences functions

View File

@ -4,6 +4,8 @@
#include "HTTP.h" #include "HTTP.h"
#include "Platform.h" #include "Platform.h"
namespace http
{
Download::Download(ByteString uri_, bool keepAlive): Download::Download(ByteString uri_, bool keepAlive):
http(NULL), http(NULL),
keepAlive(keepAlive), keepAlive(keepAlive),
@ -68,32 +70,15 @@ void Download::Start()
DownloadManager::Ref().Unlock(); DownloadManager::Ref().Unlock();
} }
// for persistent connections (keepAlive = true), reuse the open connection to make another request
bool Download::Reuse(ByteString newuri)
{
if (!keepAlive || !CheckDone() || CheckCanceled())
{
return false;
}
uri = newuri;
DownloadManager::Ref().Lock();
downloadFinished = false;
DownloadManager::Ref().Unlock();
Start();
DownloadManager::Ref().EnsureRunning();
return true;
}
// finish the download (if called before the download is done, this will block) // finish the download (if called before the download is done, this will block)
ByteString Download::Finish(int *length, int *status) ByteString Download::Finish(int *status)
{ {
if (CheckCanceled()) if (CheckCanceled())
return ""; // shouldn't happen but just in case return ""; // shouldn't happen but just in case
while (!CheckDone()); // block while (!CheckDone()); // block
DownloadManager::Ref().Lock(); DownloadManager::Ref().Lock();
downloadStarted = false; downloadStarted = false;
if (length)
*length = downloadSize;
if (status) if (status)
*status = downloadStatus; *status = downloadStatus;
ByteString ret; ByteString ret;
@ -156,7 +141,7 @@ void Download::Cancel()
DownloadManager::Ref().Unlock(); DownloadManager::Ref().Unlock();
} }
ByteString Download::Simple(ByteString uri, int *length, int *status, std::map<ByteString, ByteString> post_data) ByteString Download::Simple(ByteString uri, int *status, std::map<ByteString, ByteString> post_data)
{ {
Download *request = new Download(uri); Download *request = new Download(uri);
request->AddPostData(post_data); request->AddPostData(post_data);
@ -165,10 +150,10 @@ ByteString Download::Simple(ByteString uri, int *length, int *status, std::map<B
{ {
Platform::Millisleep(1); Platform::Millisleep(1);
} }
return request->Finish(length, status); return request->Finish(status);
} }
ByteString Download::SimpleAuth(ByteString uri, int *length, int *status, ByteString ID, ByteString session, std::map<ByteString, ByteString> post_data) ByteString Download::SimpleAuth(ByteString uri, int *status, ByteString ID, ByteString session, std::map<ByteString, ByteString> post_data)
{ {
Download *request = new Download(uri); Download *request = new Download(uri);
request->AddPostData(post_data); request->AddPostData(post_data);
@ -178,11 +163,12 @@ ByteString Download::SimpleAuth(ByteString uri, int *length, int *status, ByteSt
{ {
Platform::Millisleep(1); Platform::Millisleep(1);
} }
return request->Finish(length, status); return request->Finish(status);
} }
const char *Download::StatusText(int code) const char *StatusText(int code)
{ {
return http_ret_text(code); return http_ret_text(code);
} }
}

View File

@ -3,6 +3,8 @@
#include <map> #include <map>
#include "common/String.h" #include "common/String.h"
namespace http
{
class DownloadManager; class DownloadManager;
class Download class Download
{ {
@ -26,14 +28,13 @@ class Download
public: public:
Download(ByteString uri, bool keepAlive = false); Download(ByteString uri, bool keepAlive = false);
~Download(); virtual ~Download();
void AddPostData(std::map<ByteString, ByteString> data); void AddPostData(std::map<ByteString, ByteString> data);
void AddPostData(std::pair<ByteString, ByteString> data); void AddPostData(std::pair<ByteString, ByteString> data);
void AuthHeaders(ByteString ID, ByteString session); void AuthHeaders(ByteString ID, ByteString session);
void Start(); void Start();
bool Reuse(ByteString newuri); ByteString Finish(int *status);
ByteString Finish(int *length, int *status);
void Cancel(); void Cancel();
void CheckProgress(int *total, int *done); void CheckProgress(int *total, int *done);
@ -43,10 +44,11 @@ public:
friend class DownloadManager; friend class DownloadManager;
static ByteString Simple(ByteString uri, int *length, int *status, std::map<ByteString, ByteString> post_data = {}); static ByteString Simple(ByteString uri, int *status, std::map<ByteString, ByteString> post_data = {});
static ByteString SimpleAuth(ByteString uri, int *length, int *status, ByteString ID, ByteString session, std::map<ByteString, ByteString> post_data = {}); static ByteString SimpleAuth(ByteString uri, int *status, ByteString ID, ByteString session, std::map<ByteString, ByteString> post_data = {});
static const char *StatusText(int code);
}; };
const char *StatusText(int code);
}
#endif #endif

View File

@ -4,6 +4,8 @@
#include "Config.h" #include "Config.h"
#include "Platform.h" #include "Platform.h"
namespace http
{
DownloadManager::DownloadManager(): DownloadManager::DownloadManager():
threadStarted(false), threadStarted(false),
lastUsed(time(NULL)), lastUsed(time(NULL)),
@ -144,3 +146,4 @@ void DownloadManager::Unlock()
{ {
pthread_mutex_unlock(&downloadAddLock); pthread_mutex_unlock(&downloadAddLock);
} }
}

View File

@ -5,6 +5,8 @@
#include <vector> #include <vector>
#include "common/Singleton.h" #include "common/Singleton.h"
namespace http
{
class Download; class Download;
class DownloadManager : public Singleton<DownloadManager> class DownloadManager : public Singleton<DownloadManager>
{ {
@ -35,5 +37,6 @@ public:
void Lock(); void Lock();
void Unlock(); void Unlock();
}; };
}
#endif // DOWNLOADMANAGER_H #endif // DOWNLOADMANAGER_H

View File

@ -205,7 +205,7 @@ void http_done(void)
#ifdef WIN #ifdef WIN
WSACleanup(); WSACleanup();
#endif #endif
DownloadManager::Ref().Shutdown(); http::DownloadManager::Ref().Shutdown();
http_up = 0; http_up = 0;
} }

View File

@ -0,0 +1,39 @@
#include "ImageRequest.h"
#include "common/Singleton.h"
#include "graphics/Graphics.h"
#include "Config.h"
namespace http
{
ImageRequest::ImageRequest(ByteString url, int width, int height) :
Download(url),
Width(width),
Height(height)
{
}
std::unique_ptr<VideoBuffer> ImageRequest::Finish()
{
ByteString data = Download::Finish(nullptr);
std::unique_ptr<VideoBuffer> vb;
if (data.size())
{
int imgw, imgh;
pixel *imageData = Graphics::ptif_unpack(&data[0], data.size(), &imgw, &imgh);
if (imageData)
{
vb = std::unique_ptr<VideoBuffer>(new VideoBuffer(imageData, imgw, imgh));
free(imageData);
}
else
{
vb = std::unique_ptr<VideoBuffer>(new VideoBuffer(32, 32));
vb->SetCharacter(14, 14, 'x', 255, 255, 255, 255);
}
vb->Resize(Width, Height, true);
}
return vb;
}
}

24
src/client/ImageRequest.h Normal file
View File

@ -0,0 +1,24 @@
#ifndef IMAGEREQUEST2_H
#define IMAGEREQUEST2_H
#include "Download.h"
#include "common/String.h"
#include <memory>
class VideoBuffer;
namespace http
{
class ImageRequest : public Download
{
int Width, Height;
public:
ImageRequest(ByteString url, int width, int height);
std::unique_ptr<VideoBuffer> Finish();
};
}
#endif // IMAGEREQUEST2_H

View File

@ -108,13 +108,6 @@ void RequestBroker::RetrieveThumbnail(int saveID, int saveDate, int width, int h
RetrieveImage(url.Build(), width, height, tListener); RetrieveImage(url.Build(), width, height, tListener);
} }
void RequestBroker::RetrieveAvatar(ByteString username, int width, int height, RequestListener * tListener)
{
ByteString url = ByteString::Build("http://", STATICSERVER, "/avatars/", username, ".pti");
RetrieveImage(url, width, height, tListener);
}
void RequestBroker::Start(Request * request, RequestListener * tListener, int identifier) void RequestBroker::Start(Request * request, RequestListener * tListener, int identifier)
{ {
ListenerHandle handle = AttachRequestListener(tListener); ListenerHandle handle = AttachRequestListener(tListener);

View File

@ -56,7 +56,6 @@ public:
void RenderThumbnail(GameSave * gameSave, int width, int height, RequestListener * tListener); void RenderThumbnail(GameSave * gameSave, int width, int height, RequestListener * tListener);
void RetrieveThumbnail(int saveID, int saveDate, int width, int height, RequestListener * tListener); void RetrieveThumbnail(int saveID, int saveDate, int width, int height, RequestListener * tListener);
void RetrieveThumbnail(int saveID, int width, int height, RequestListener * tListener); void RetrieveThumbnail(int saveID, int width, int height, RequestListener * tListener);
void RetrieveAvatar(ByteString username, int width, int height, RequestListener * tListener);
void Start(Request * request, RequestListener * tLIstener, int identifier = 0); void Start(Request * request, RequestListener * tLIstener, int identifier = 0);
bool CheckRequestListener(ListenerHandle handle); bool CheckRequestListener(ListenerHandle handle);

View File

@ -4,7 +4,7 @@
#include "AvatarButton.h" #include "AvatarButton.h"
#include "Format.h" #include "Format.h"
#include "client/Client.h" #include "client/Client.h"
#include "client/requestbroker/RequestBroker.h" #include "client/AvatarRequest.h"
#include "graphics/Graphics.h" #include "graphics/Graphics.h"
#include "ContextMenu.h" #include "ContextMenu.h"
#include "Keys.h" #include "Keys.h"
@ -14,7 +14,7 @@ namespace ui {
AvatarButton::AvatarButton(Point position, Point size, ByteString username): AvatarButton::AvatarButton(Point position, Point size, ByteString username):
Component(position, size), Component(position, size),
avatar(NULL), avatarRequest(nullptr),
name(username), name(username),
tried(false), tried(false),
actionCallback(NULL) actionCallback(NULL)
@ -24,8 +24,6 @@ AvatarButton::AvatarButton(Point position, Point size, ByteString username):
AvatarButton::~AvatarButton() AvatarButton::~AvatarButton()
{ {
RequestBroker::Ref().DetachRequestListener(this);
delete avatar;
delete actionCallback; delete actionCallback;
} }
@ -34,17 +32,14 @@ void AvatarButton::Tick(float dt)
if(!avatar && !tried && name.size() > 0) if(!avatar && !tried && name.size() > 0)
{ {
tried = true; tried = true;
RequestBroker::Ref().RetrieveAvatar(name, Size.X, Size.Y, this); avatarRequest = new http::AvatarRequest(name, Size.X, Size.Y);
avatarRequest->Start();
} }
}
void AvatarButton::OnResponseReady(void * imagePtr, int identifier) if (avatarRequest && avatarRequest->CheckDone())
{
VideoBuffer * image = (VideoBuffer*)imagePtr;
if(image)
{ {
delete avatar; avatar = avatarRequest->Finish();
avatar = image; avatarRequest = nullptr;
} }
} }
@ -54,7 +49,7 @@ void AvatarButton::Draw(const Point& screenPos)
if(avatar) if(avatar)
{ {
g->draw_image(avatar, screenPos.X, screenPos.Y, 255); g->draw_image(avatar.get(), screenPos.X, screenPos.Y, 255);
} }
} }

View File

@ -8,6 +8,12 @@
#include "gui/interface/Colour.h" #include "gui/interface/Colour.h"
#include "client/requestbroker/RequestListener.h" #include "client/requestbroker/RequestListener.h"
#include <memory>
namespace http
{
class AvatarRequest;
}
namespace ui namespace ui
{ {
class AvatarButton; class AvatarButton;
@ -18,9 +24,10 @@ public:
virtual ~AvatarButtonAction() {} virtual ~AvatarButtonAction() {}
}; };
class AvatarButton : public Component, public RequestListener class AvatarButton : public Component
{ {
VideoBuffer * avatar; std::unique_ptr<VideoBuffer> avatar;
http::AvatarRequest *avatarRequest;
ByteString name; ByteString name;
bool tried; bool tried;
public: public:
@ -38,8 +45,6 @@ public:
void Draw(const Point& screenPos) override; void Draw(const Point& screenPos) override;
void Tick(float dt) override; void Tick(float dt) override;
void OnResponseReady(void * imagePtr, int identifier) override;
void DoAction(); void DoAction();
void SetUsername(ByteString username) { name = username; } void SetUsername(ByteString username) { name = username; }

View File

@ -75,13 +75,13 @@ void PreviewModel::UpdateSave(int saveID, int saveDate)
url = ByteString::Build("http://", STATICSERVER, "/", saveID, "_", saveDate, ".cps"); url = ByteString::Build("http://", STATICSERVER, "/", saveID, "_", saveDate, ".cps");
else else
url = ByteString::Build("http://", STATICSERVER, "/", saveID, ".cps"); url = ByteString::Build("http://", STATICSERVER, "/", saveID, ".cps");
saveDataDownload = new Download(url); saveDataDownload = new http::Download(url);
saveDataDownload->Start(); saveDataDownload->Start();
url = ByteString::Build("http://", SERVER , "/Browse/View.json?ID=", saveID); url = ByteString::Build("http://", SERVER , "/Browse/View.json?ID=", saveID);
if (saveDate) if (saveDate)
url += ByteString::Build("&Date=", saveDate); url += ByteString::Build("&Date=", saveDate);
saveInfoDownload = new Download(url); saveInfoDownload = new http::Download(url);
saveInfoDownload->AuthHeaders(ByteString::Build(Client::Ref().GetAuthUser().UserID), Client::Ref().GetAuthUser().SessionID); saveInfoDownload->AuthHeaders(ByteString::Build(Client::Ref().GetAuthUser().UserID), Client::Ref().GetAuthUser().SessionID);
saveInfoDownload->Start(); saveInfoDownload->Start();
@ -90,7 +90,7 @@ void PreviewModel::UpdateSave(int saveID, int saveDate)
commentsLoaded = false; commentsLoaded = false;
url = ByteString::Build("http://", SERVER, "/Browse/Comments.json?ID=", saveID, "&Start=", (commentsPageNumber-1)*20, "&Count=20"); url = ByteString::Build("http://", SERVER, "/Browse/Comments.json?ID=", saveID, "&Start=", (commentsPageNumber-1)*20, "&Count=20");
commentsDownload = new Download(url); commentsDownload = new http::Download(url);
commentsDownload->AuthHeaders(ByteString::Build(Client::Ref().GetAuthUser().UserID), Client::Ref().GetAuthUser().SessionID); commentsDownload->AuthHeaders(ByteString::Build(Client::Ref().GetAuthUser().UserID), Client::Ref().GetAuthUser().SessionID);
commentsDownload->Start(); commentsDownload->Start();
} }
@ -142,7 +142,7 @@ void PreviewModel::UpdateComments(int pageNumber)
if (!GetDoOpen()) if (!GetDoOpen())
{ {
ByteString url = ByteString::Build("http://", SERVER, "/Browse/Comments.json?ID=", saveID, "&Start=", (commentsPageNumber-1)*20, "&Count=20"); ByteString url = ByteString::Build("http://", SERVER, "/Browse/Comments.json?ID=", saveID, "&Start=", (commentsPageNumber-1)*20, "&Count=20");
commentsDownload = new Download(url); commentsDownload = new http::Download(url);
commentsDownload->AuthHeaders(ByteString::Build(Client::Ref().GetAuthUser().UserID), Client::Ref().GetAuthUser().SessionID); commentsDownload->AuthHeaders(ByteString::Build(Client::Ref().GetAuthUser().UserID), Client::Ref().GetAuthUser().SessionID);
commentsDownload->Start(); commentsDownload->Start();
} }
@ -239,7 +239,7 @@ bool PreviewModel::ParseSaveInfo(ByteString &saveInfoResponse)
saveDataDownload->Cancel(); saveDataDownload->Cancel();
delete saveData; delete saveData;
saveData = NULL; saveData = NULL;
saveDataDownload = new Download(ByteString::Build("http://", STATICSERVER, "/2157797.cps")); saveDataDownload = new http::Download(ByteString::Build("http://", STATICSERVER, "/2157797.cps"));
saveDataDownload->Start(); saveDataDownload->Start();
} }
return true; return true;
@ -283,8 +283,8 @@ void PreviewModel::Update()
{ {
if (saveDataDownload && saveDataDownload->CheckDone()) if (saveDataDownload && saveDataDownload->CheckDone())
{ {
int status, length; int status;
ByteString ret = saveDataDownload->Finish(&length, &status); ByteString ret = saveDataDownload->Finish(&status);
ByteString nothing; ByteString nothing;
Client::Ref().ParseServerReturn(nothing, status, true); Client::Ref().ParseServerReturn(nothing, status, true);
@ -308,7 +308,7 @@ void PreviewModel::Update()
if (saveInfoDownload && saveInfoDownload->CheckDone()) if (saveInfoDownload && saveInfoDownload->CheckDone())
{ {
int status; int status;
ByteString ret = saveInfoDownload->Finish(NULL, &status); ByteString ret = saveInfoDownload->Finish(&status);
ByteString nothing; ByteString nothing;
Client::Ref().ParseServerReturn(nothing, status, true); Client::Ref().ParseServerReturn(nothing, status, true);
@ -336,7 +336,7 @@ void PreviewModel::Update()
if (commentsDownload && commentsDownload->CheckDone()) if (commentsDownload && commentsDownload->CheckDone())
{ {
int status; int status;
ByteString ret = commentsDownload->Finish(NULL, &status); ByteString ret = commentsDownload->Finish(&status);
ClearComments(); ClearComments();
ByteString nothing; ByteString nothing;

View File

@ -23,9 +23,9 @@ class PreviewModel {
void notifyCommentsPageChanged(); void notifyCommentsPageChanged();
void notifyCommentBoxEnabledChanged(); void notifyCommentBoxEnabledChanged();
Download * saveDataDownload; http::Download * saveDataDownload;
Download * saveInfoDownload; http::Download * saveInfoDownload;
Download * commentsDownload; http::Download * commentsDownload;
int saveID; int saveID;
int saveDate; int saveDate;

View File

@ -26,7 +26,7 @@ private:
virtual bool doWork() virtual bool doWork()
{ {
String error; String error;
Download *request = new Download(updateName); http::Download *request = new http::Download(updateName);
request->Start(); request->Start();
notifyStatus("Downloading update"); notifyStatus("Downloading update");
notifyProgress(-1); notifyProgress(-1);
@ -38,8 +38,8 @@ private:
Platform::Millisleep(1); Platform::Millisleep(1);
} }
int dataLength, status; int status;
ByteString data = request->Finish(&dataLength, &status); ByteString data = request->Finish(&status);
if (status!=200) if (status!=200)
{ {
error = String::Build("Server responded with Status ", status); error = String::Build("Server responded with Status ", status);
@ -58,9 +58,9 @@ private:
unsigned int uncompressedLength; unsigned int uncompressedLength;
if(dataLength<16) if(data.size()<16)
{ {
error = String::Build("Unsufficient data, got ", dataLength, " bytes"); error = String::Build("Unsufficient data, got ", data.size(), " bytes");
goto corrupt; goto corrupt;
} }
if (data[0]!=0x42 || data[1]!=0x75 || data[2]!=0x54 || data[3]!=0x54) if (data[0]!=0x42 || data[1]!=0x75 || data[2]!=0x54 || data[3]!=0x54)
@ -83,7 +83,7 @@ private:
} }
int dstate; int dstate;
dstate = BZ2_bzBuffToBuffDecompress((char *)res, (unsigned *)&uncompressedLength, &data[8], dataLength-8, 0, 0); dstate = BZ2_bzBuffToBuffDecompress((char *)res, (unsigned *)&uncompressedLength, &data[8], data.size()-8, 0, 0);
if (dstate) if (dstate)
{ {
error = String::Build("Unable to decompress update: ", dstate); error = String::Build("Unable to decompress update: ", dstate);

View File

@ -1354,15 +1354,15 @@ int luatpt_getscript(lua_State* l)
if (confirmPrompt && !ConfirmPrompt::Blocking("Do you want to install script?", url.FromUtf8(), "Install")) if (confirmPrompt && !ConfirmPrompt::Blocking("Do you want to install script?", url.FromUtf8(), "Install"))
return 0; return 0;
int ret, len; int ret;
ByteString scriptData = Download::Simple(url, &len, &ret); ByteString scriptData = http::Download::Simple(url, &ret);
if (len <= 0 || !filename) if (!scriptData.size() || !filename)
{ {
return luaL_error(l, "Server did not return data"); return luaL_error(l, "Server did not return data");
} }
if (ret != 200) if (ret != 200)
{ {
return luaL_error(l, Download::StatusText(ret)); return luaL_error(l, http::StatusText(ret));
} }
if (!strcmp(scriptData.c_str(), "Invalid script ID\r\n")) if (!strcmp(scriptData.c_str(), "Invalid script ID\r\n"))