Skip to content

Commit

Permalink
remake logging; config refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
bakatrouble committed May 2, 2020
1 parent 06bb98a commit 4354095
Show file tree
Hide file tree
Showing 8 changed files with 178 additions and 51 deletions.
13 changes: 4 additions & 9 deletions src/config.cpp
Original file line number Diff line number Diff line change
@@ -1,23 +1,18 @@
#include <iostream>
#include <inih.h>
#include <set>
#include <sstream>
#include "config.hpp"
#include "utils.hpp"
#include "logger.hpp"

using namespace std;

Config Config::load() {
Config conf;
conf.refresh();
return conf;
}

bool Config::refresh() {
INIReader reader("sdmc:/config/sys-screenuploader/config.ini");

if (reader.ParseError() != 0) {
cout << "Config parse error " << reader.ParseError() << endl;
Logger::get().error() << "Config parse error " << reader.ParseError() << endl;
error = true;
return false;
}

Expand Down Expand Up @@ -57,7 +52,7 @@ bool Config::refresh() {
}
}

m_url = reader.Get("server", "url", "https://screenuploader.bakatrouble.me/upload/" + URLplaceholder + "/");
m_url = reader.Get("server", "url", defaultUrl);

if (reader.Sections().count("url_params") > 0) {
for (auto &key : reader.Fields("url_params")) {
Expand Down
13 changes: 10 additions & 3 deletions src/config.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,26 @@ using namespace std;


const string URLplaceholder = "<destid>";
const string defaultUrl = "https://screenuploader.bakatrouble.me/upload/" + URLplaceholder + "/";

class Config {
public:
static Config load();
static Config& get() {
static Config instance;
return instance;
}

bool refresh();

string getUrl(string &tid);
string getUrlParams();
bool uploadAllowed(string &tid, bool isMovie);
bool keepLogs();

protected:
string m_url = "https://screenuploader.bakatrouble.me/upload/" + URLplaceholder + "/";
bool error;

private:
string m_url;
string m_defaultDestID;
bool m_uploadScreenshots;
bool m_uploadMovies;
Expand Down
115 changes: 115 additions & 0 deletions src/logger.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
#pragma once

#include <iostream>
#include <fstream>
#include <ctime>

using namespace std;


enum LogLevel {
DEBUG = 0,
INFO = 1,
ERROR = 2,
NONE = 10,
};

const string LOGFILE_PATH = "sdmc:/config/sys-screenuploader/screenuploader.log";

class Logger {
public:
static Logger& get() {
static Logger instance;
return instance;
}

void truncate() {
close();
m_file.open(LOGFILE_PATH, ios::trunc);
close();
}

void setLevel(LogLevel level) {
m_level = level;
}

void open() {
if (!m_file.is_open()) {
m_file.open(LOGFILE_PATH, ios::app);
}
}

void close() {
if (m_file.is_open()) {
m_file.close();
}
}

bool isEnabled(LogLevel level) {
return level >= m_level;
}

ostream &debug() {
if (isEnabled(DEBUG)) {
open();
m_file << getPrefix(DEBUG);
return m_file;
}
return cout;
}

ostream &info() {
if (isEnabled(INFO)) {
open();
m_file << getPrefix(INFO);
return m_file;
}
return cout;
}

ostream &error() {
if (isEnabled(ERROR)) {
open();
m_file << getPrefix(ERROR);
return m_file;
}
return cout;
}

ostream &none() {
if (isEnabled(NONE)) {
open();
m_file << getPrefix(NONE);
return m_file;
}
return cout;
}

private:
static string get_time() {
u64 now;
timeGetCurrentTime(TimeType_LocalSystemClock, &now);
time_t nowt = now;
char buf[sizeof "2011-10-08 07:07:09 UTC"];
strftime(buf, sizeof buf, "%F %T UTC", gmtime(&nowt));
return buf;
}

static string getPrefix(LogLevel lvl) {
string prefix;
switch(lvl) {
case DEBUG:
prefix = "[DEBUG] "; break;
case INFO:
prefix = "[INFO ] "; break;
case ERROR:
prefix = "[ERROR] "; break;
default:
prefix = "[ ] "; break;
}
return prefix + "[" + get_time() + "] ";
}

ofstream m_file;
LogLevel m_level = INFO;
};
61 changes: 35 additions & 26 deletions src/main.cpp
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
#include <netinet/in.h>
#include <switch.h>
#include <fstream>
#include <dirent.h>
#include <iostream>
#include "upload.hpp"
#include "utils.hpp"
#include "config.hpp"
#include "logger.hpp"
#include "project.h"

using namespace std;
Expand Down Expand Up @@ -90,11 +90,16 @@ extern "C" {
if (R_FAILED(rc))
fatalThrow(rc);

rc = timeInitialize();
if (R_FAILED(rc))
fatalThrow(rc);

fsdevMountSdmc();
}

void __appExit(void) {
fsdevUnmountAll();
timeExit();
fsExit();
capsaExit();
pminfoExit();
Expand All @@ -105,14 +110,14 @@ extern "C" {
}
}

static ofstream log;
void initLogger(bool truncate) {
if (truncate)
Logger::get().get().truncate();

void openLogFile(bool truncate) {
log = ofstream ("sdmc:/config/sys-screenuploader/screenuploader.log", truncate ? ios::trunc : ios::app);
cout.rdbuf(log.rdbuf());
cerr.rdbuf(log.rdbuf());
cout << "=============================" << endl << endl << endl;
cout << "ScreenUploader v" << APP_VERSION << " is starting..." << endl;
Logger::get().none() << "=============================" << endl;
Logger::get().none() << "=============================" << endl;
Logger::get().none() << "=============================" << endl;
Logger::get().none() << "ScreenUploader v" << APP_VERSION << " is starting..." << endl;
}

#pragma clang diagnostic push
Expand All @@ -121,55 +126,59 @@ int main(int argc, char **argv) {
mkdir("sdmc:/config", 0700);
mkdir("sdmc:/config/sys-screenuploader", 0700);

openLogFile(false);
Config conf = Config::load();
if (!conf.keepLogs()) {
log.close();
openLogFile(true);
}
initLogger(false);
Config::get().refresh();
if (Config::get().error)
return 0;

if (!Config::get().keepLogs())
initLogger(true);

Result rc;
CapsAlbumStorage storage;
FsFileSystem imageFs;
rc = capsaGetAutoSavingStorage(&storage);
if (!R_SUCCEEDED(rc)) {
cout << "capsaGetAutoSavingStorage() failed: " << rc << ", exiting..." << endl;
Logger::get().error() << "capsaGetAutoSavingStorage() failed: " << rc << ", exiting..." << endl;
return 0;
}
rc = fsOpenImageDirectoryFileSystem(&imageFs, (FsImageDirectoryId)storage);
if (!R_SUCCEEDED(rc)) {
cout << "fsOpenImageDirectoryFileSystem() failed: " << rc << ", exiting..." << endl;
Logger::get().error() << "fsOpenImageDirectoryFileSystem() failed: " << rc << ", exiting..." << endl;
return 0;
}
int mountRes = fsdevMountDevice("img", imageFs);
if (mountRes < 0) {
cout << "fsdevMountDevice() failed, exiting..." << endl;
Logger::get().error() << "fsdevMountDevice() failed, exiting..." << endl;
return 0;
}
cout << "Mounted " << (storage ? "SD" : "NAND") << " storage" << endl;
Logger::get().info() << "Mounted " << (storage ? "SD" : "NAND") << " storage" << endl;

string tmpItem, lastItem = getLastAlbumItem(conf);
cout << "Current last item: " << lastItem << endl;
string tmpItem, lastItem = getLastAlbumItem();
Logger::get().info() << "Current last item: " << lastItem << endl;
Logger::get().close();

size_t fs;
while (true) {
tmpItem = getLastAlbumItem(conf);
tmpItem = getLastAlbumItem();
if (lastItem.compare(tmpItem) < 0) {
fs = filesize(tmpItem);
if (fs > 0) {
cout << "=============================" << endl;
cout << "New item found: " << tmpItem << endl;
cout << "Filesize: " << fs << endl;
Logger::get().info() << "=============================" << endl;
Logger::get().info() << "New item found: " << tmpItem << endl;
Logger::get().info() << "Filesize: " << fs << endl;
bool sent = false;
for (int i=0; i<3; i++) {
sent = sendFileToServer(conf, tmpItem, fs);
sent = sendFileToServer(tmpItem, fs);
if (sent)
break;
}
lastItem = tmpItem;
if (!sent)
cout << "Unable to send file after 3 retries" << endl;
Logger::get().error() << "Unable to send file after 3 retries" << endl;
}

Logger::get().close();
}

svcSleepThread(1e+9);
Expand Down
21 changes: 11 additions & 10 deletions src/upload.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#include <filesystem>
#include <curl/curl.h>
#include "config.hpp"
#include "logger.hpp"

namespace fs = filesystem;

Expand All @@ -28,11 +29,11 @@ static size_t _uploadReadFunction(void *ptr, size_t size, size_t nmemb, void *da
return 0;
}

bool sendFileToServer(Config &conf, string &path, size_t size) {
bool sendFileToServer(string &path, size_t size) {
string tid = path.substr(path.length() - 36, 32);
cout << "Title ID: " << tid << endl;
if (!conf.uploadAllowed(tid, path.back() == '4')) {
cout << "Not uploading" << endl;
Logger::get().debug() << "Title ID: " << tid << endl;
if (!Config::get().uploadAllowed(tid, path.back() == '4')) {
Logger::get().info() << "Not uploading" << endl;
return true;
}

Expand All @@ -41,7 +42,7 @@ bool sendFileToServer(Config &conf, string &path, size_t size) {
FILE *f = fopen(path.c_str(), "rb");

if (f == nullptr) {
cout << "fopen() failed" << endl;
Logger::get().error() << "fopen() failed" << endl;
return false;
}

Expand All @@ -50,8 +51,8 @@ bool sendFileToServer(Config &conf, string &path, size_t size) {
CURL *curl = curl_easy_init();
if (curl) {
stringstream url;
url << conf.getUrl(tid) << "?filename=" << fpath.filename().string() << conf.getUrlParams() ;
cout << "Upload URL: " << url.str() << endl;
url << Config::get().getUrl(tid) << "?filename=" << fpath.filename().string() << Config::get().getUrlParams() ;
Logger::get().debug() << "Upload URL: " << url.str() << endl;
curl_easy_setopt(curl, CURLOPT_URL, url.str().c_str());
curl_easy_setopt(curl, CURLOPT_POST, 1L);
struct curl_slist *chunk = nullptr;
Expand All @@ -75,17 +76,17 @@ bool sendFileToServer(Config &conf, string &path, size_t size) {
double requestSize;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &responseCode);
curl_easy_getinfo(curl, CURLINFO_SIZE_UPLOAD, &requestSize);
cout << requestSize << " bytes sent, response code: " << responseCode << endl;
Logger::get().debug() << requestSize << " bytes sent, response code: " << responseCode << endl;
curl_slist_free_all(chunk);
curl_easy_cleanup(curl);
return responseCode == 200;
} else {
cout << "curl_easy_perform() failed: " << curl_easy_strerror(res) << endl;
Logger::get().error() << "curl_easy_perform() failed: " << curl_easy_strerror(res) << endl;
curl_slist_free_all(chunk);
curl_easy_cleanup(curl);
return false;
}
}
cout << "curl_easy_init() failed" << endl;
Logger::get().error() << "curl_easy_init() failed" << endl;
return false;
}
2 changes: 1 addition & 1 deletion src/upload.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@

using namespace std;

bool sendFileToServer(Config &conf, string &path, size_t size);
bool sendFileToServer(string &path, size_t size);
2 changes: 1 addition & 1 deletion src/utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ bool isDigitsOnly(const string &str) {
return str.find_first_not_of("0123456789") == string::npos;
}

string getLastAlbumItem(Config &conf) {
string getLastAlbumItem() {
vector<string> years, months, days, files;
string albumPath = getAlbumPath();
if (!fs::is_directory(albumPath)) return "<No album directory: " + albumPath + ">";
Expand Down
2 changes: 1 addition & 1 deletion src/utils.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ using namespace std;
namespace fs = filesystem;


string getLastAlbumItem(Config &conf);
string getLastAlbumItem();
size_t filesize(string &path);
string url_encode(const string &value);

0 comments on commit 4354095

Please sign in to comment.