2 Copyright (C) 2015 Carl Hetherington <cth@carlh.net>
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 #include "curl_uploader.h"
21 #include "exceptions.h"
24 #include "compose.hpp"
31 using boost::function;
34 read_callback (void* ptr, size_t size, size_t nmemb, void* object)
36 CurlUploader* u = reinterpret_cast<CurlUploader*> (object);
37 return u->read_callback (ptr, size, nmemb);
40 CurlUploader::CurlUploader (function<void (string)> set_status, function<void (float)> set_progress)
41 : Uploader (set_status, set_progress)
46 _curl = curl_easy_init ();
48 throw NetworkError (_("Could not start transfer"));
51 curl_easy_setopt (_curl, CURLOPT_READFUNCTION, ::read_callback);
52 curl_easy_setopt (_curl, CURLOPT_READDATA, this);
53 curl_easy_setopt (_curl, CURLOPT_UPLOAD, 1L);
54 curl_easy_setopt (_curl, CURLOPT_FTP_CREATE_MISSING_DIRS, 1L);
55 curl_easy_setopt (_curl, CURLOPT_READDATA, this);
56 curl_easy_setopt (_curl, CURLOPT_USERNAME, Config::instance()->tms_user().c_str ());
57 curl_easy_setopt (_curl, CURLOPT_PASSWORD, Config::instance()->tms_password().c_str ());
60 CurlUploader::~CurlUploader ()
65 curl_easy_cleanup (_curl);
69 CurlUploader::create_directory (boost::filesystem::path)
71 /* this is done by libcurl */
75 CurlUploader::upload_file (boost::filesystem::path from, boost::filesystem::path to, boost::uintmax_t& transferred, boost::uintmax_t total_size)
79 String::compose ("ftp://%1/%2/%3", Config::instance()->tms_ip(), Config::instance()->tms_path(), to.string ()).c_str ()
82 _file = fopen_boost (from, "rb");
84 throw NetworkError (String::compose (_("Could not open %1 to send"), from));
86 _transferred = &transferred;
87 _total_size = total_size;
89 CURLcode const r = curl_easy_perform (_curl);
91 throw NetworkError (String::compose (_("Could not write to remote file (%1)"), curl_easy_strerror (r)));
98 CurlUploader::read_callback (void* ptr, size_t size, size_t nmemb)
100 size_t const r = fread (ptr, size, nmemb, _file);
101 *_transferred += size * nmemb;
103 if (_total_size > 0) {
104 _set_progress ((double) *_transferred / _total_size);