CLOUD: Cleanup in Handlers

Simplified some stuff here and there by using HandlerUtils static
methods.
This commit is contained in:
Alexander Tkachev 2016-07-09 17:06:50 +06:00
parent f1830645d0
commit 36b0069e95
12 changed files with 57 additions and 286 deletions

View file

@ -58,7 +58,6 @@ ifdef USE_SDL_NET
MODULE_OBJS += \ MODULE_OBJS += \
networking/sdl_net/client.o \ networking/sdl_net/client.o \
networking/sdl_net/getclienthandler.o \ networking/sdl_net/getclienthandler.o \
networking/sdl_net/handlers/basehandler.o \
networking/sdl_net/handlers/createdirectoryhandler.o \ networking/sdl_net/handlers/createdirectoryhandler.o \
networking/sdl_net/handlers/downloadfilehandler.o \ networking/sdl_net/handlers/downloadfilehandler.o \
networking/sdl_net/handlers/filesbasehandler.o \ networking/sdl_net/handlers/filesbasehandler.o \

View file

@ -1,100 +0,0 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "backends/networking/sdl_net/handlers/basehandler.h"
#include "common/archive.h"
#include "common/config-manager.h"
#include "common/file.h"
#include "common/unzip.h"
namespace Networking {
#define ARCHIVE_NAME "wwwroot.zip"
BaseHandler::BaseHandler() {}
BaseHandler::~BaseHandler() {}
/// utils
Common::Archive *BaseHandler::getZipArchive() const {
// first search in themepath
if (ConfMan.hasKey("themepath")) {
const Common::FSNode &node = Common::FSNode(ConfMan.get("themepath"));
if (!node.exists() || !node.isReadable() || !node.isDirectory())
return nullptr;
Common::FSNode fileNode = node.getChild(ARCHIVE_NAME);
if (fileNode.exists() && fileNode.isReadable() && !fileNode.isDirectory()) {
Common::SeekableReadStream *const stream = fileNode.createReadStream();
Common::Archive *zipArchive = Common::makeZipArchive(stream);
if (zipArchive) return zipArchive;
}
}
// then use SearchMan to find it
Common::ArchiveMemberList fileList;
SearchMan.listMatchingMembers(fileList, ARCHIVE_NAME);
for (Common::ArchiveMemberList::iterator it = fileList.begin(); it != fileList.end(); ++it) {
Common::ArchiveMember const &m = **it;
Common::SeekableReadStream *const stream = m.createReadStream();
Common::Archive *zipArchive = Common::makeZipArchive(stream);
if (zipArchive) return zipArchive;
}
return nullptr;
}
Common::ArchiveMemberList BaseHandler::listArchive() const {
Common::ArchiveMemberList resultList;
Common::Archive *zipArchive = getZipArchive();
if (zipArchive) {
zipArchive->listMembers(resultList);
delete zipArchive;
}
return resultList;
}
Common::SeekableReadStream *BaseHandler::getArchiveFile(Common::String name) const {
Common::SeekableReadStream *result = nullptr;
Common::Archive *zipArchive = getZipArchive();
if (zipArchive) {
const Common::ArchiveMemberPtr ptr = zipArchive->getMember(name);
if (ptr.get() == nullptr) return nullptr;
result = ptr->createReadStream();
delete zipArchive;
}
return result;
}
Common::String BaseHandler::readEverythingFromStream(Common::SeekableReadStream *const stream) {
Common::String result;
char buf[1024];
uint32 readBytes;
while (!stream->eos()) {
readBytes = stream->read(buf, 1024);
result += Common::String(buf, readBytes);
}
return result;
}
} // End of namespace Networking

View file

@ -24,7 +24,6 @@
#define BACKENDS_NETWORKING_SDL_NET_BASEHANDLER_H #define BACKENDS_NETWORKING_SDL_NET_BASEHANDLER_H
#include "backends/networking/sdl_net/client.h" #include "backends/networking/sdl_net/client.h"
#include "common/archive.h"
#include "common/callback.h" #include "common/callback.h"
namespace Networking { namespace Networking {
@ -32,15 +31,9 @@ namespace Networking {
typedef Common::BaseCallback<Client &> *ClientHandlerCallback; typedef Common::BaseCallback<Client &> *ClientHandlerCallback;
class BaseHandler { class BaseHandler {
protected:
Common::Archive *getZipArchive() const;
Common::ArchiveMemberList listArchive() const;
Common::SeekableReadStream *getArchiveFile(Common::String name) const;
static Common::String readEverythingFromStream(Common::SeekableReadStream *const stream);
public: public:
BaseHandler(); BaseHandler() {}
virtual ~BaseHandler(); virtual ~BaseHandler() {}
virtual ClientHandlerCallback getHandler() = 0; virtual ClientHandlerCallback getHandler() = 0;
}; };

View file

@ -21,15 +21,13 @@
*/ */
#include "backends/networking/sdl_net/handlers/createdirectoryhandler.h" #include "backends/networking/sdl_net/handlers/createdirectoryhandler.h"
#include "backends/networking/sdl_net/localwebserver.h"
#include "backends/fs/fs-factory.h" #include "backends/fs/fs-factory.h"
#include "common/file.h" #include "backends/networking/sdl_net/handlerutils.h"
#include "backends/networking/sdl_net/localwebserver.h"
#include "common/translation.h" #include "common/translation.h"
namespace Networking { namespace Networking {
#define INDEX_PAGE_NAME ".index.html"
CreateDirectoryHandler::CreateDirectoryHandler() {} CreateDirectoryHandler::CreateDirectoryHandler() {}
CreateDirectoryHandler::~CreateDirectoryHandler() {} CreateDirectoryHandler::~CreateDirectoryHandler() {}
@ -37,75 +35,29 @@ CreateDirectoryHandler::~CreateDirectoryHandler() {}
void CreateDirectoryHandler::handle(Client &client) { void CreateDirectoryHandler::handle(Client &client) {
Common::String path = client.queryParameter("path"); Common::String path = client.queryParameter("path");
Common::String name = client.queryParameter("directory_name"); Common::String name = client.queryParameter("directory_name");
Common::String errorMessage = "";
// show an error message if failed to create directory
if (!createDirectory(path, name, errorMessage)) {
handleErrorMessage(
client,
Common::String::format(
"%s<br/><a href=\"files?path=%s\">%s</a>",
errorMessage.c_str(),
"%2F", //that's encoded "/"
_("Back to the files manager")
)
);
return;
}
Common::String response = "<html><head><title>ScummVM</title></head><body>{message}</body></html>";
// load stylish response page from the archive
Common::SeekableReadStream *const stream = getArchiveFile(INDEX_PAGE_NAME);
if (stream) response = readEverythingFromStream(stream);
replace(response, "{message}", Common::String::format(
"%s<br/><a href=\"files?path=%s\">%s</a>",
_("Directory created successfully!"),
client.queryParameter("path").c_str(),
_("Back to parent directory")
)
);
LocalWebserver::setClientRedirectHandler(
client, response,
"/files?path=" + LocalWebserver::urlEncodeQueryParameterValue(client.queryParameter("path"))
);
}
void CreateDirectoryHandler::handleErrorMessage(Client &client, Common::String message) {
Common::String response = "<html><head><title>ScummVM</title></head><body>{message}</body></html>";
// load stylish response page from the archive
Common::SeekableReadStream *const stream = getArchiveFile(INDEX_PAGE_NAME);
if (stream) response = readEverythingFromStream(stream);
replace(response, "{message}", message);
LocalWebserver::setClientGetHandler(client, response);
}
bool CreateDirectoryHandler::createDirectory(Common::String path, Common::String name, Common::String &errorMessage) {
// check that <path> is not an absolute root // check that <path> is not an absolute root
if (path == "" || path == "/") { if (path == "" || path == "/") {
errorMessage = _("Can't create directory here!"); HandlerUtils::setFilesManagerErrorMessageHandler(client, _("Can't create directory here!"));
return false; return;
} }
// transform virtual path to actual file system one // transform virtual path to actual file system one
Common::String prefixToRemove = "", prefixToAdd = ""; Common::String prefixToRemove = "", prefixToAdd = "";
if (!transformPath(path, prefixToRemove, prefixToAdd) || path.empty()) { if (!transformPath(path, prefixToRemove, prefixToAdd) || path.empty()) {
errorMessage = _("Invalid path!"); HandlerUtils::setFilesManagerErrorMessageHandler(client, _("Invalid path!"));
return false; return;
} }
// check that <path> exists and is directory // check that <path> exists and is directory
AbstractFSNode *node = g_system->getFilesystemFactory()->makeFileNodePath(path); AbstractFSNode *node = g_system->getFilesystemFactory()->makeFileNodePath(path);
if (!node->exists()) { if (!node->exists()) {
errorMessage = _("Parent directory doesn't exists!"); HandlerUtils::setFilesManagerErrorMessageHandler(client, _("Parent directory doesn't exists!"));
return false; return;
} }
if (!node->isDirectory()) { if (!node->isDirectory()) {
errorMessage = _("Can't create a directory within a file!"); HandlerUtils::setFilesManagerErrorMessageHandler(client, _("Can't create a directory within a file!"));
return false; return;
} }
// check that <directory_name> doesn't exist or is directory // check that <directory_name> doesn't exist or is directory
@ -113,18 +65,28 @@ bool CreateDirectoryHandler::createDirectory(Common::String path, Common::String
node = g_system->getFilesystemFactory()->makeFileNodePath(path + name); node = g_system->getFilesystemFactory()->makeFileNodePath(path + name);
if (node->exists()) { if (node->exists()) {
if (!node->isDirectory()) { if (!node->isDirectory()) {
errorMessage = _("There is a file with that name in the parent directory!"); HandlerUtils::setFilesManagerErrorMessageHandler(client, _("There is a file with that name in the parent directory!"));
return false; return;
} else return true;
} }
} else {
// create the <directory_name> in <path> // create the <directory_name> in <path>
if (!node->create(true)) { if (!node->create(true)) {
errorMessage = _("Failed to create the directory!"); HandlerUtils::setFilesManagerErrorMessageHandler(client, _("Failed to create the directory!"));
return false; return;
}
} }
return true; // set redirect on success
HandlerUtils::setMessageHandler(
client,
Common::String::format(
"%s<br/><a href=\"files?path=%s\">%s</a>",
_("Directory created successfully!"),
client.queryParameter("path").c_str(),
_("Back to parent directory")
),
"/files?path=" + LocalWebserver::urlEncodeQueryParameterValue(client.queryParameter("path"))
);
} }
/// public /// public

View file

@ -29,16 +29,6 @@ namespace Networking {
class CreateDirectoryHandler: public FilesBaseHandler { class CreateDirectoryHandler: public FilesBaseHandler {
void handle(Client &client); void handle(Client &client);
void handleErrorMessage(Client &client, Common::String message);
/**
* Creates the directory <name> in <path>.
*
* Fills <errorMessage> on failure.
*
* Returns true on success.
*/
bool createDirectory(Common::String path, Common::String name, Common::String &errorMessage);
public: public:
CreateDirectoryHandler(); CreateDirectoryHandler();
virtual ~CreateDirectoryHandler(); virtual ~CreateDirectoryHandler();

View file

@ -21,77 +21,48 @@
*/ */
#include "backends/networking/sdl_net/handlers/downloadfilehandler.h" #include "backends/networking/sdl_net/handlers/downloadfilehandler.h"
#include "backends/networking/sdl_net/localwebserver.h"
#include "backends/fs/fs-factory.h" #include "backends/fs/fs-factory.h"
#include "common/file.h" #include "backends/networking/sdl_net/getclienthandler.h"
#include "backends/networking/sdl_net/handlerutils.h"
#include "backends/networking/sdl_net/localwebserver.h"
#include "common/translation.h" #include "common/translation.h"
#include "../getclienthandler.h"
namespace Networking { namespace Networking {
#define INDEX_PAGE_NAME ".index.html"
DownloadFileHandler::DownloadFileHandler() {} DownloadFileHandler::DownloadFileHandler() {}
DownloadFileHandler::~DownloadFileHandler() {} DownloadFileHandler::~DownloadFileHandler() {}
void DownloadFileHandler::handle(Client &client) { void DownloadFileHandler::handle(Client &client) {
Common::String path = client.queryParameter("path"); Common::String path = client.queryParameter("path");
Common::String errorMessage = "";
// show an error message if failed to download the file
if (!downloadFile(client, path, errorMessage)) {
handleErrorMessage(
client,
Common::String::format(
"%s<br/><a href=\"files?path=%s\">%s</a>",
errorMessage.c_str(),
"%2F", //that's encoded "/"
_("Back to the files manager")
)
);
}
}
void DownloadFileHandler::handleErrorMessage(Client &client, Common::String message) {
Common::String response = "<html><head><title>ScummVM</title></head><body>{message}</body></html>";
// load stylish response page from the archive
Common::SeekableReadStream *const stream = getArchiveFile(INDEX_PAGE_NAME);
if (stream) response = readEverythingFromStream(stream);
replace(response, "{message}", message);
LocalWebserver::setClientGetHandler(client, response);
}
bool DownloadFileHandler::downloadFile(Client &client, Common::String path, Common::String &errorMessage) {
// check that <path> is not an absolute root // check that <path> is not an absolute root
if (path == "" || path == "/") { if (path == "" || path == "/") {
errorMessage = _("Invalid path!"); HandlerUtils::setFilesManagerErrorMessageHandler(client, _("Invalid path!"));
return false; return;
} }
// transform virtual path to actual file system one // transform virtual path to actual file system one
Common::String prefixToRemove = "", prefixToAdd = ""; Common::String prefixToRemove = "", prefixToAdd = "";
if (!transformPath(path, prefixToRemove, prefixToAdd, false) || path.empty()) { if (!transformPath(path, prefixToRemove, prefixToAdd, false) || path.empty()) {
errorMessage = _("Invalid path!"); HandlerUtils::setFilesManagerErrorMessageHandler(client, _("Invalid path!"));
return false; return;
} }
// check that <path> exists and is directory // check that <path> exists and is directory
AbstractFSNode *node = g_system->getFilesystemFactory()->makeFileNodePath(path); AbstractFSNode *node = g_system->getFilesystemFactory()->makeFileNodePath(path);
if (!node->exists()) { if (!node->exists()) {
errorMessage = _("The file doesn't exist!"); HandlerUtils::setFilesManagerErrorMessageHandler(client, _("The file doesn't exist!"));
return false; return;
} }
if (node->isDirectory()) { if (node->isDirectory()) {
errorMessage = _("Can't download a directory!"); HandlerUtils::setFilesManagerErrorMessageHandler(client, _("Can't download a directory!"));
return false; return;
} }
Common::SeekableReadStream *stream = node->createReadStream(); Common::SeekableReadStream *stream = node->createReadStream();
if (stream == nullptr) { if (stream == nullptr) {
errorMessage = _("Failed to read the file!"); HandlerUtils::setFilesManagerErrorMessageHandler(client, _("Failed to read the file!"));
return false; return;
} }
GetClientHandler *handler = new GetClientHandler(stream); GetClientHandler *handler = new GetClientHandler(stream);
@ -100,7 +71,6 @@ bool DownloadFileHandler::downloadFile(Client &client, Common::String path, Comm
handler->setHeader("Content-Disposition", "attachment; filename=\"" + node->getDisplayName() + "\""); handler->setHeader("Content-Disposition", "attachment; filename=\"" + node->getDisplayName() + "\"");
handler->setHeader("Content-Transfer-Encoding", "binary"); handler->setHeader("Content-Transfer-Encoding", "binary");
client.setHandler(handler); client.setHandler(handler);
return true;
} }
/// public /// public

View file

@ -29,16 +29,6 @@ namespace Networking {
class DownloadFileHandler: public FilesBaseHandler { class DownloadFileHandler: public FilesBaseHandler {
void handle(Client &client); void handle(Client &client);
void handleErrorMessage(Client &client, Common::String message);
/**
* Creates a client handler for downloading file <path>.
*
* Fills <errorMessage> on failure.
*
* Returns true on success.
*/
bool downloadFile(Client &client, Common::String path, Common::String &errorMessage);
public: public:
DownloadFileHandler(); DownloadFileHandler();
virtual ~DownloadFileHandler(); virtual ~DownloadFileHandler();

View file

@ -21,8 +21,8 @@
*/ */
#include "backends/networking/sdl_net/handlers/filespagehandler.h" #include "backends/networking/sdl_net/handlers/filespagehandler.h"
#include "backends/networking/sdl_net/handlerutils.h"
#include "backends/networking/sdl_net/localwebserver.h" #include "backends/networking/sdl_net/localwebserver.h"
#include "common/file.h"
#include "common/translation.h" #include "common/translation.h"
namespace Networking { namespace Networking {
@ -52,23 +52,15 @@ void FilesPageHandler::handle(Client &client) {
Common::String itemTemplate = "<tr><td><a href=\"{link}\">{name}</a></td><td>{size}</td></tr>\n"; //TODO: load this template too? Common::String itemTemplate = "<tr><td><a href=\"{link}\">{name}</a></td><td>{size}</td></tr>\n"; //TODO: load this template too?
// load stylish response page from the archive // load stylish response page from the archive
Common::SeekableReadStream *const stream = getArchiveFile(FILES_PAGE_NAME); Common::SeekableReadStream *const stream = HandlerUtils::getArchiveFile(FILES_PAGE_NAME);
if (stream) response = readEverythingFromStream(stream); if (stream) response = HandlerUtils::readEverythingFromStream(stream);
Common::String path = client.queryParameter("path"); Common::String path = client.queryParameter("path");
Common::String content = ""; Common::String content = "";
// show an error message if failed to list directory // show an error message if failed to list directory
if (!listDirectory(path, content, itemTemplate)) { if (!listDirectory(path, content, itemTemplate)) {
handleErrorMessage( HandlerUtils::setFilesManagerErrorMessageHandler(client, _("ScummVM couldn't list the directory you specified."));
client,
Common::String::format(
"%s<br/><a href=\"files?path=%s\">%s</a>",
_("ScummVM couldn't list the directory you specified."),
"%2F", //that's encoded "/"
_("Back to the files manager")
)
);
return; return;
} }
@ -85,17 +77,6 @@ void FilesPageHandler::handle(Client &client) {
LocalWebserver::setClientGetHandler(client, response); LocalWebserver::setClientGetHandler(client, response);
} }
void FilesPageHandler::handleErrorMessage(Client &client, Common::String message) {
Common::String response = "<html><head><title>ScummVM</title></head><body>{message}</body></html>";
// load stylish response page from the archive
Common::SeekableReadStream *const stream = getArchiveFile(INDEX_PAGE_NAME);
if (stream) response = readEverythingFromStream(stream);
replace(response, "{message}", message);
LocalWebserver::setClientGetHandler(client, response);
}
bool FilesPageHandler::listDirectory(Common::String path, Common::String &content, const Common::String &itemTemplate) { bool FilesPageHandler::listDirectory(Common::String path, Common::String &content, const Common::String &itemTemplate) {
if (path == "" || path == "/") { if (path == "" || path == "/") {
addItem(content, itemTemplate, true, "/root/", _("File system root")); addItem(content, itemTemplate, true, "/root/", _("File system root"));

View file

@ -29,7 +29,6 @@ namespace Networking {
class FilesPageHandler: public FilesBaseHandler { class FilesPageHandler: public FilesBaseHandler {
void handle(Client &client); void handle(Client &client);
void handleErrorMessage(Client &client, Common::String message);
/** /**
* Lists the directory <path>. * Lists the directory <path>.

View file

@ -21,47 +21,33 @@
*/ */
#include "backends/networking/sdl_net/handlers/indexpagehandler.h" #include "backends/networking/sdl_net/handlers/indexpagehandler.h"
#include "backends/networking/sdl_net/handlerutils.h"
#include "backends/networking/sdl_net/localwebserver.h" #include "backends/networking/sdl_net/localwebserver.h"
#include "backends/saves/default/default-saves.h"
#include "common/archive.h"
#include "common/config-manager.h"
#include "common/file.h"
#include "common/savefile.h"
#include "common/translation.h" #include "common/translation.h"
#include "gui/storagewizarddialog.h" #include "gui/storagewizarddialog.h"
namespace Networking { namespace Networking {
#define INDEX_PAGE_NAME ".index.html"
IndexPageHandler::IndexPageHandler(): CommandSender(nullptr) {} IndexPageHandler::IndexPageHandler(): CommandSender(nullptr) {}
IndexPageHandler::~IndexPageHandler() {} IndexPageHandler::~IndexPageHandler() {}
void IndexPageHandler::handle(Client &client) { void IndexPageHandler::handle(Client &client) {
Common::String response = "<html><head><title>ScummVM</title></head><body>{message}</body></html>";
// load stylish response page from the archive
Common::SeekableReadStream *const stream = getArchiveFile(INDEX_PAGE_NAME);
if (stream) response = readEverythingFromStream(stream);
Common::String code = client.queryParameter("code"); Common::String code = client.queryParameter("code");
if (code == "") { if (code == "") {
replace(response, "{message}", _("This is a local webserver index page.")); HandlerUtils::setMessageHandler(client, _("This is a local webserver index page."));
LocalWebserver::setClientGetHandler(client, response);
return; return;
} }
_code = code; _code = code;
sendCommand(GUI::kStorageCodePassedCmd, 0); sendCommand(GUI::kStorageCodePassedCmd, 0);
replace(response, "{message}", _("ScummVM got the code and already connects to your cloud storage!")); HandlerUtils::setMessageHandler(client, _("ScummVM got the code and already connects to your cloud storage!"));
LocalWebserver::setClientGetHandler(client, response);
} }
/// public /// public
Common::String IndexPageHandler::code() { return _code; } Common::String IndexPageHandler::code() const { return _code; }
ClientHandlerCallback IndexPageHandler::getHandler() { ClientHandlerCallback IndexPageHandler::getHandler() {
return new Common::Callback<IndexPageHandler, Client &>(this, &IndexPageHandler::handle); return new Common::Callback<IndexPageHandler, Client &>(this, &IndexPageHandler::handle);

View file

@ -37,7 +37,7 @@ public:
IndexPageHandler(); IndexPageHandler();
virtual ~IndexPageHandler(); virtual ~IndexPageHandler();
Common::String code(); Common::String code() const;
virtual ClientHandlerCallback getHandler(); virtual ClientHandlerCallback getHandler();
}; };

View file

@ -21,6 +21,7 @@
*/ */
#include "backends/networking/sdl_net/handlers/resourcehandler.h" #include "backends/networking/sdl_net/handlers/resourcehandler.h"
#include "backends/networking/sdl_net/handlerutils.h"
#include "backends/networking/sdl_net/localwebserver.h" #include "backends/networking/sdl_net/localwebserver.h"
namespace Networking { namespace Networking {
@ -37,7 +38,7 @@ void ResourceHandler::handle(Client &client) {
if (filename.size() && filename[0] == '.') return; if (filename.size() && filename[0] == '.') return;
// if file not found, don't set handler either // if file not found, don't set handler either
Common::SeekableReadStream *file = getArchiveFile(filename); Common::SeekableReadStream *file = HandlerUtils::getArchiveFile(filename);
if (file == nullptr) return; if (file == nullptr) return;
LocalWebserver::setClientGetHandler(client, file, 200, LocalWebserver::determineMimeType(filename)); LocalWebserver::setClientGetHandler(client, file, 200, LocalWebserver::determineMimeType(filename));