How to convert fs:path to variable - c++

Ok, firstly, I'm new to this. So yell at me as much as you like, but try to be useful at the same time :)
So I'm attempting to build a plugin using C++ to find a log file, and upload to a FTP every few minutes. The idea is to allow administrators to see the logs without needing direct access to the server. The ftp was the easy bit of this, running #include <CkFtp2.h> to do most of this with ease. I then used fs::path to find the latest file edited. Which looked like this:
//finding the latest file
int FindFile() {
fs::path latest;
std::time_t latest_tm {};
for (auto&& entry : boost::make_iterator_range(fs::directory_iterator("."), {})) {
fs::path p = entry.path();
if (is_regular_file(p) && p.extension() == ".txt")
{
std::time_t timestamp = fs::last_write_time(p);
if (timestamp > latest_tm) {
latest = p;
latest_tm = timestamp;
}
}
}
}
I now want to define string localFilename = latest however I get error: no viable conversion from 'fs::path' to 'string. Could someone help me?
Check out my github here to see what I'm working on and how I want this to implement with the rest of the code: https://github.com/TGTGamer/sourcebansLogMonitoring/blob/master/SourcebansToFTP.sp
p.s. If i'm being stupid, tell me the answer then slap me round the face....

Related

Using Json.cpp in Cocos2dx v4

https://github.com/cocos2d/cocos2d-x/blob/v4/cocos/editor-support/spine/Json.cpp
I need help loading a .txt and pulling out some text using cocos for an old App. Can anyone work up a simple example?
The backstory is that I wrote a working app about 5-6 years ago when cocos used a different json library. They changed the library and I can't decipher the new one enough to get it working again. I am not a programmer, but made the app as a favor for a hospital. The json is used to switch between languages for the script. I don't really even know how to ask a technical question about the library. I know the code is all there, but I don't know how to make it work...
Thanks :)
cocos2dx v4 Json implementation
This is what I figured out eventually. Any improvements you can suggest are welcome.
I use this to read json-response from a translation api:
std::vector<char> * buffer = response->getResponseData();
char * concatenated = (char *) malloc(buffer->size() + 1);
std::string s2(buffer->begin(), buffer->end());
strcpy(concatenated, s2.c_str());
CCLOG ("DEBUG |%s|", concatenated);
Json * json = Json_create(concatenated);
Json *responseData = Json_getItem(json, "responseData");
const char * var22 = Json_getString(responseData, "translatedText", "default");
USED JSON response
{"responseData":
{"translatedText":"ni\u00f1o"}, .....
and copyed the old json.c and json.h in my classes dir.
static void readCurve (Json* frame, spCurveTimeline* timeline, int frameIndex) {
Json* curve = Json_getItem(frame, "curve");
if (!curve) return;
if (curve->type == Json_String && strcmp(curve->valueString, "stepped") == 0)
spCurveTimeline_setStepped(timeline, frameIndex);
else if (curve->type == Json_Array) {
Json* child0 = curve->child;
Json* child1 = child0->next;
Json* child2 = child1->next;
Json* child3 = child2->next;
spCurveTimeline_setCurve(timeline, frameIndex, child0->valueFloat, child1->valueFloat, child2->valueFloat,
child3->valueFloat);
}
}

VivoxCore for Unreal Engine 4

Has anyone used VivoxCore for unreal engine 4 and know what this error means? I'm not able to really understand what this means. I've tried reading through the source code for vivox, as well as the documentation and that error code (1105) is mentioned nowhere. Also, the company which makes this does not respond to emails, and their public forum is not active. I've tried calling them, emailing them, using the public forum, reading online for answers, and I've found nothing, so stackoverflow is my last option. I hope someone here can help me.
LogVivoxVoiceChat: Warning: onConnectFailed server:https://vdx5.www.vivox.com/api2 error:SIP Backend Required (1105)
Here is my code:
VoiceChat = (FVivoxVoiceChat*)FVivoxVoiceChat::Get();
if (!VoiceChat->IsInitialized())
{
GLog->Log("Is not initialized, trying to initialize.");
VoiceChat->Initialize();
return;
}
if (!VoiceChat->IsConnected())
{
GLog->Log("Is not connected, trying to connect.");
VoiceChat->Connect(FOnVoiceChatConnectCompleteDelegate::CreateLambda([](const FVoiceChatResult& Result)
{
}));
return;
}
FString PlayerName = PlayerState->GetPlayerName();
FString LoginToken = VoiceChat->InsecureGetLoginToken(PlayerName);
if (!VoiceChat->IsLoggedIn())
{
GLog->Log("Is not logged in, trying to login.");
VoiceChat->Login(0, PlayerName, LoginToken, FOnVoiceChatLoginCompleteDelegate::CreateLambda([](const FString& LoggedInPlayerName, const FVoiceChatResult& Result)
{
}));
return;
}
FString ChannelName = "TestChannel";
EVoiceChatChannelType ChannelType = EVoiceChatChannelType::Echo; // Echo for testing.
TOptional<FVoiceChatChannel3dProperties> Channel3dProperties;
FString JoinToken = VoiceChat->InsecureGetJoinToken(ChannelName, ChannelType, Channel3dProperties);
VoiceChat->JoinChannel(ChannelName, JoinToken, ChannelType, FOnVoiceChatChannelJoinCompleteDelegate::CreateLambda([](const FString& JoinedChannelName, const FVoiceChatResult& Result)
{
GLog->Log("JOin Channel successful");
}), Channel3dProperties);
VoiceChat->TransmitToSpecificChannel(ChannelName);
This error means that you have an outdated SDK. The SDK included in UE4 is outdated: it is using backend version 4, but the actual version is 5.
Try disabling the Vivox Interface plugin if it's enabled.

Some Problems of Indy 10 IdHTTP Implementation

In regard to Indy 10 of IdHTTP, many things have been running perfectly, but there are a few things that don't work so well here. That is why, once again, I need your help.
Download button has been running perfectly. I'm using the following code :
void __fastcall TForm1::DownloadClick(TObject *Sender)
{
MyFile = SaveDialog->FileName;
TFileStream* Fist = new TFileStream(MyFile, fmCreate | fmShareDenyNone);
Download->Enabled = false;
Urlz = Edit1->Text;
Url->Caption = Urlz;
try
{
IdHTTP->Get(Edit1->Text, Fist);
IdHTTP->Connected();
IdHTTP->Response->ResponseCode = 200;
IdHTTP->ReadTimeout = 70000;
IdHTTP->ConnectTimeout = 70000;
IdHTTP->ReuseSocket;
Fist->Position = 0;
}
__finally
{
delete Fist;
Form1->Updated();
}
}
However, a "Cancel Resume" button is still can't resume interrupted downloads. Meant, it is always sending back the entire file every time I call Get() though I've used IdHTTP->Request->Ranges property.
I use the following code:
void __fastcall TForm1::CancelResumeClick(TObject *Sender)
{
MyFile = SaveDialog->FileName;;
TFileStream* TFist = new TFileStream(MyFile, fmCreate | fmShareDenyNone);
if (IdHTTP->Connected() == true)
{
IdHTTP->Disconnect();
CancelResume->Caption = "RESUME";
IdHTTP->Response->AcceptRanges = "Bytes";
}
else
{
try {
CancelResume->Caption = "CANCEL";
// IdHTTP->Request->Ranges == "0-100";
// IdHTTP->Request->Range = Format("bytes=%d-",ARRAYOFCONST((TFist->Position)));
IdHTTP->Request->Ranges->Add()->StartPos = TFist->Position;
IdHTTP->Get(Edit1->Text, TFist);
IdHTTP->Request->Referer = Edit1->Text;
IdHTTP->ConnectTimeout = 70000;
IdHTTP->ReadTimeout = 70000;
}
__finally {
delete TFist;
}
}
Meanwhile, by using the FormatBytes function, found here, has been able to shows only the size of download files. But still unable to determine the speed of download or transfer speed.
I'm using the following code:
void __fastcall TForm1::IdHTTPWork(TObject *ASender, TWorkMode AWorkMode, __int64 AWorkCount)
{
__int64 Romeo = 0;
Romeo = IdHTTP->Response->ContentStream->Position;
// Romeo = AWorkCount;
Download->Caption = FormatBytes(Romeo) + " (" + IntToStr(Romeo) + " Bytes)";
ForSpeed->Caption = FormatBytes(Romeo);
ProgressBar->Position = AWorkCount;
ProgressBar->Update();
Form1->Updated();
}
Please advise and give an example. Any help would sure be appreciated!
In your DownloadClick() method:
Calling Connected() is useless, since you don't do anything with the result. Nor is there any guarantee that the connection will remain connected, as the server could send a Connection: close response header. I don't see anything in your code that is asking for HTTP keep-alives. Let TIdHTTP manage the connection for you.
You are forcing the Response->ResponseCode to 200. Don't do that. Respect the response code that the server actually sent. The fact that no exception was raised means the response was successful whether it is 200 or 206.
You are reading the ReuseSocket property value and ignoring it.
There is no need to reset the Fist->Position property to 0 before closing the file.
Now, with that said, your CancelResumeClick() method has many issues.
You are using the fmCreate flag when opening the file. If the file already exists, you will overwrite it from scratch, thus TFist->Position will ALWAYS be 0. Use fmOpenReadWrite instead so an existing file will open as-is. And then you have to seek to the end of the file to provide the correct Position to the Ranges header.
You are relying on the socket's Connected() state to make decisions. DO NOT do that. The connection may be gone after the previous response, or may have timed out and been closed before the new request is made. The file can still be resumed either way. HTTP is stateless. It does not matter if the socket remains open between requests, or is closed in between. Every request is self-contained. Use information provided in the previous response to govern the next request. Not the socket state.
You are modifying the value of the Response->AcceptRanges property, instead of using the value provided by the previous response. The server tells you if the file supports resuming, so you have to remember that value, or query it before then attempting to resumed download.
When you actually call Get(), the server may or may not respect the requested Range, depending on whether the requested file supports byte ranges or not. If the server responds with a response code of 206, the requested range is accepted, and the server sends ONLY the requested bytes, so you need to APPEND them to your existing file. However, if the server response with a response code of 200, the server is sending the entire file from scratch, so you need to REPLACE your existing file with the new bytes. You are not taking that into account.
In your IdHTTPWork() method, in order to calculate the download/transfer speed, you have to keep track of how many bytes are actually being transferred in between each event firing. When the event is fired, save the current AWorkCount and tick count, and then the next time the event is fired, you can compare the new AWorkCount and current ticks to know how much time has elapsed and how many bytes were transferred. From those value, you can calculate the speed, and even the estimated time remaining.
As for your progress bar, you can't use AWorkCount alone to calculate a new position. That only works if you set the progress bar's Max to AWorkCountMax in the OnWorkBegin event, and that value is not always know before a download begins. You need to take into account the size of the file being downloaded, whether it is being downloaded fresh or being resumed, how many bytes are being requested during a resume, etc. So there is lot more work involved in displaying a progress bar for a HTTP download.
Now, to answer your two questions:
How to retrieve and save the download file to a disk by using its original name?
It is provided by the server in the filename parameter of the Content-Disposition header, and/or in the name parameter of the Content-Type header. If neither value is provided by the server, you can use the filename that is in the URL you are requesting. TIdHTTP has a URL property that provides the parsed version of the last requested URL.
However, since you are creating the file locally before sending your download request, you will have to create a local file using a temp filename, and then rename the local file after the download is complete. Otherwise, use TIdHTTP.Head() to determine the real filename (you can also use it to determine if resuming is supported) before creating the local file with that filename, then use TIdHTTP.Get() to download to that local file. Otherwise, download the file to memory using TMemoryStream instead of TFileStream, and then save with the desired filename when complete.
when I click http://get.videolan.org/vlc/2.2.1/win32/vlc-2.2.1-win32.exe then the server will process requests to its actual url. http://mirror.vodien.com/videolan/vlc/2.2.1/win32/vlc-2.2.1-win32.exe. The problem is that IdHTTP will not automatically grab through it.
That is because VideoLan is not using an HTTP redirect to send clients to the real URL (TIdHTTP supports HTTP redirects). VideoLan is using an HTML redirect instead (TIdHTTP does not support HTML redirects). When a webbrowser downloads the first URL, a 5 second countdown timer is displayed before the real download then begins. As such, you will have to manually detect that the server is sending you an HTML page instead of the real file (look at the TIdHTTP.Response.ContentType property for that), parse the HTML to determine the real URL, and then download it. This also means that you cannot download the first URL directly into your target local file, otherwise you will corrupt it, especially during a resume. You have to cache the server's response first, either to a temp file or to memory, so you can analyze it before deciding how to act on it. It also means you have to remember the real URL for resuming, you cannot resume the download using the original countdown URL.
Try something more like the following instead. It does not take into account for everything mentioned above (particularly speed/progress tracking, HTML redirects, etc), but should get you a little closer:
void __fastcall TForm1::DownloadClick(TObject *Sender)
{
Urlz = Edit1->Text;
Url->Caption = Urlz;
IdHTTP->Head(Urlz);
String FileName = IdHTTP->Response->RawHeaders->Params["Content-Disposition"]["filename"];
if (FileName.IsEmpty())
{
FileName = IdHTTP->Response->RawHeaders->Params["Content-Type"]["name"];
if (FileName.IsEmpty())
FileName = IdHTTP->URL->Document;
}
SaveDialog->FileName = FileName;
if (!SaveDialog->Execute()) return;
MyFile = SaveDialog->FileName;
TFileStream* Fist = new TFileStream(MyFile, fmCreate | fmShareDenyWrite);
try
{
try
{
Download->Enabled = false;
Resume->Enabled = false;
IdHTTP->Request->Clear();
//...
IdHTTP->ReadTimeout = 70000;
IdHTTP->ConnectTimeout = 70000;
IdHTTP->Get(Urlz, Fist);
}
__finally
{
delete Fist;
Download->Enabled = true;
Updated();
}
}
catch (const EIdHTTPProtocolException &)
{
DeleteFile(MyFile);
throw;
}
}
void __fastcall TForm1::ResumeClick(TObject *Sender)
{
TFileStream* Fist = new TFileStream(MyFile, fmOpenReadWrite | fmShareDenyWrite);
try
{
Download->Enabled = false;
Resume->Enabled = false;
IdHTTP->Request->Clear();
//...
Fist->Seek(0, soEnd);
IdHTTP->Request->Ranges->Add()->StartPos = Fist->Position;
IdHTTP->Request->Referer = Edit1->Text;
IdHTTP->ConnectTimeout = 70000;
IdHTTP->ReadTimeout = 70000;
IdHTTP->Get(Urlz, Fist);
}
__finally
{
delete Fist;
Download->Enabled = true;
Updated();
}
}
void __fastcall TForm1::IdHTTPHeadersAvailable(TObject*Sender, TIdHeaderList *AHeaders, bool &VContinue)
{
Resume->Enabled = ( ((IdHTTP->Response->ResponseCode == 200) || (IdHTTP->Response->ResponseCode == 206)) && TextIsSame(AHeaders->Values["Accept-Ranges"], "bytes") );
if ((IdHTTP->Response->ContentStream) && (IdHTTP->Request->Ranges->Count > 0) && (IdHTTP->Response->ResponseCode == 200))
IdHTTP->Response->ContentStream->Size = 0;
}
#Romeo:
Also, you can try a following function to determine the real download filename.
I've translated this to C++ based on the RRUZ'function. So far so good, I'm using it on my simple IdHTTP download program, too.
But, this translation result is of course still need value improvement input from Remy Lebeau, RRUZ, or any other master here.
String __fastcall GetRemoteFileName(const String URI)
{
String result;
try
{
TIdHTTP* HTTP = new TIdHTTP(NULL);
try
{
HTTP->Head(URI);
result = HTTP->Response->RawHeaders->Params["Content-Disposition"]["filename"];
if (result.IsEmpty())
{
result = HTTP->Response->RawHeaders->Params["Content-Type"]["name"];
if (result.IsEmpty())
result = HTTP->URL->Document;
}
}
__finally
{
delete HTTP;
}
}
catch(const Exception &ex)
{
ShowMessage(const_cast<Exception&>(ex).ToString());
}
return result;
}

Gtksourceviewmm syntax highlighting not working

I'm trying to use the C++ wrapper gtksourceview, I made this a long time ago and I remember that it was working, but now everything works except the higlight syntax. And I'm not pretty sure what it is. I hope you can help me, I read a lot about this library on internet but I can find a solution. Here is a simple code. Thanks in advance.
#include "twindow.h"
#include <iostream>
TWindow::TWindow() {
add(m_SourceView);
m_SourceView.set_size_request(640, 480);
m_SourceView.set_show_line_numbers();
m_SourceView.set_tab_width(4);
m_SourceView.set_auto_indent();
m_SourceView.set_show_right_margin();
m_SourceView.set_right_margin_position(80);
m_SourceView.set_highlight_current_line();
m_SourceView.set_smart_home_end(gtksourceview::SOURCE_SMART_HOME_END_ALWAYS);
gtksourceview::init ();
Glib::RefPtr<gtksourceview::SourceBuffer> buffer = m_SourceView.get_source_buffer () ;
if (!buffer) {
std::cerr << "gtksourceview::SourceView::get_source_buffer () failed" << std::endl ;
}
buffer->begin_not_undoable_action();
buffer->set_text(Glib::file_get_contents("main.c"));
buffer->end_not_undoable_action();
buffer->set_highlight_syntax(true);
Glib::RefPtr<gtksourceview::SourceLanguageManager> language_manager = gtksourceview::SourceLanguageManager::create();
Glib::RefPtr<gtksourceview::SourceLanguage> language = gtksourceview::SourceLanguage::create();
language = language_manager->get_language("c");
buffer->set_language(language);
show_all_children();
}
So you want to use the c++ wrapper of gtksourceview, so I guess you want to use gtksourceviewmm.
Why you create the LanguageManager, you can use the default one.
If you using 3.2 of gtksourceviewmm, then look at the docs.
You should also check out this function.
So an example would look like;
Glib::ustring file_path = "/home/user/whatever/main.c";
Glib::RefPtr<Gsv::LanguageManager> language_manager = Gsv::LanguageManager::get_default();
Glib::RefPtr<Gsv::Language> language = language_manager->guess_language(file_path, Glib::ustring());
Another thing I want to mention is that you should create a buffer to show the content of the file, as in my projects I got a seg fault when I wanted to use get_source_buffer(), so it seems to be null by default.
Glib::RefPtr<Gsv::Buffer> buffer = Gsv::Buffer::create(language);
buffer->set_text(Glib::get_file_contents(file_path));
this->m_SourceView.set_source_buffer(buffer);

How can I compress backup log files?

I'm using log4cplus in my project to do logging.
I created logger.conf and I will load it in the beginning of my application.
This is my logger.conf:
log4cplus.appender.Developer=log4cplus::RollingFileAppender
log4cplus.appender.Developer.DatePattern = ".yyyy-MM-dd"
log4cplus.appender.Developer.Schedule = HOURLY
log4cplus.appender.Developer.File=log/developer.log
log4cplus.appender.Developer.MaxFileSize=3MB
log4cplus.appender.Developer.MaxBackupIndex=10
log4cplus.appender.Developer.layout=log4cplus::PatternLayout
log4cplus.appender.Developer.layout.ContextPrinting=enabled
log4cplus.appender.Developer.layout.ConversionPattern=%D{%Y-%m-%d %H:%M:%S,%Q} [%t] %p - %m%n
log4cplus.appender.Developer.Threshold=TRACE
log4cplus.logger.DEVELOPER=TRACE, Developer
This is how I load my logger.conf:
QString log_path = qApp->applicationDirPath() + "/log";
QDir().mkpath(log_path);
PropertyConfigurator logger(L"configs/logger.conf", Logger::getDefaultHierarchy());
logger.configure();
And whenever I want to log, I use the following line:
Logger::getInstance(L"DEVELOPER").log(INFO_LOG_LEVEL, L"..............");
I'd like to know two things:
How can I tell Log4Cplus to compress the backup logs?
In some post I saw this reply:
I need to create my own appender, inheriting from RollingFileAppender and then add a compression steps.
If it's possible, can anyone tell me how to do it, please? I don't know how to implement this.
How can I add a pattern to the name of these backup logs?
At the moment, Log4Cplus makes my back up like this:
developer.log.1
developer.log.2
developer.log.3
...
I'd like to add date and time to it.
You will need to implement you own Appender like this:
class NewFileAppender : public ::log4cplus::RollingFileAppender
{
void
newFileAppender::rollover()
{
helpers::LogLog & loglog = getLogLog();
// Close the current file
out.close();
out.clear(); // reset flags since the C++ standard specified that all the
// flags should remain unchanged on a close
// If maxBackups <= 0, then there is no file renaming to be done.
if (maxBackupIndex > 0)
{
rolloverCompressedFiles(filename, maxBackupIndex);
// Rename fileName to fileName.DATE
tstring target = filename + DATE;
int ret;
ret = file_rename (filename, target);
//TODO: compress using zlib
}
}
}