downloader/dwn.cpp
#include "wx/wx.h"
#include "wx/xrc/xmlres.h"
#include <wx/event.h>
#include <wx/msgdlg.h>
#include "gui.cpp"
#include <curl/curl.h>
int continueDownload=0;
size_t writecallback(void *buffer, size_t size, size_t nmemb, void *stream)
{
int written = fwrite(buffer, size, nmemb, (FILE *)stream);
return written;
}
class ThDownload : public wxThread
{
public:
wxString url, dest;
wxFrame *fr;
wxGauge *bar;
wxStaticText *lblStatus, *lblTitle;
ThDownload();
private:
virtual void *Entry();
};
ThDownload::ThDownload()
{
}
int progressDownload( wxGauge* b,
curl_off_t t, /* dltotal */
curl_off_t d, /* dlnow */
curl_off_t ultotal,
curl_off_t ulnow)
{
int p=0;
curl_off_t percento=0;
if (t>0) percento= d*100/t;
p=(int)percento;
printf("P=%d%\n",p);
wxTheApp->CallAfter( [p, b] {
b->SetValue(p);
});
return continueDownload;
}
void *ThDownload::Entry()
{
CURL *curl;
CURLcode res;
char errbuf[CURL_ERROR_SIZE];
//long httpFail;
curl = curl_easy_init();
if(curl) {
const char* murl = this->url.c_str();
curl_easy_setopt(curl, CURLOPT_URL, murl);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writecallback);
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_XFERINFODATA, this->bar);
curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, progressDownload);
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);
const char* mdest = this->dest.c_str();
FILE *f = fopen(mdest,"wb");
if (f == NULL) {
curl_easy_cleanup(curl);
}
curl_easy_setopt(curl,CURLOPT_WRITEDATA, f);
res = curl_easy_perform(curl);
if(res != CURLE_OK)
{
size_t len = strlen(errbuf);
if(len)
{
printf("Error: %s\n", errbuf);
wxString m =wxString::FromUTF8(errbuf);
this->lblTitle->SetLabel("Error! ");
this->lblStatus->SetLabel(m);
wxMessageBox(m, "Error:", wxICON_EXCLAMATION|wxICON_ERROR, this->fr);
}
}
//if (httpFail>=400) g_print("Problema http: %ld\n", httpFail);
curl_easy_cleanup(curl);
fclose(f);
this->fr->Close();
}
return 0;
}
class DwnFrame{
public:
wxFrame frame0;
wxStaticText *lblTitle;
wxStaticText *lblStatus;
wxGauge *bar;
wxString url,dest;
ThDownload *thread;
void ShowFrame();
void Download(wxString url, wxString dest);
void quit(wxCloseEvent& event);
} ;
void DwnFrame::quit(wxCloseEvent& event)
{
printf("Quit.");
continueDownload=-1;
this->frame0.Close();
}
void DwnFrame::ShowFrame()
{
wxXmlResource::Get()->LoadFrame(&frame0, NULL, wxT("frame0"));
lblTitle = XRCCTRL(frame0, "lblTitle", wxStaticText);
lblStatus = XRCCTRL(frame0, "lblStatus", wxStaticText);
bar=XRCCTRL(frame0, "bar", wxGauge);
frame0.Bind(wxEVT_CLOSE_WINDOW, &DwnFrame::quit, this);
frame0.Show();
}
void DwnFrame::Download(wxString url, wxString dest)
{
this->thread = new ThDownload();
thread->url=url;
thread->dest=dest;
thread->fr=&this->frame0;
thread->bar=this->bar;
thread->lblTitle=this->lblTitle;
thread->lblStatus=this->lblStatus;
thread->Create();
thread->Run();
}