C++ Voice Package Download and MD5 Check with Improved Error Handling and Resource Management
void Property::DownloadAndCheck(const std::string& url, const std::string& md5, const std::string& id) { std::string dest_file = VOIP_DOWNLOAD_FILE;
LOGD("DownloadAndCheck, %s url is > %s : md5sum is > %s", dest_file.c_str(), url.c_str(), md5.c_str());
std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(dest_file.c_str(), "wb"), &fclose);
if (!fp) {
throw SysIOException(dest_file + " : open failed");
}
std::unique_ptr<CURL, decltype(&curl_easy_cleanup)> curl(curl_easy_init(), &curl_easy_cleanup);
if (!curl) {
throw SysIOException("curl_easy_init failed");
}
curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 0);
curl_easy_setopt(curl.get(), CURLOPT_XFERINFOFUNCTION, progress_func);
curl_easy_setopt(curl.get(), CURLOPT_XFERINFODATA, this);
curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, &Property::WriteFunc);
curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, fp.get());
curl_easy_setopt(curl.get(), CURLOPT_CONNECTTIMEOUT, 30);
curl_easy_setopt(curl.get(), CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl.get(), CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(curl.get(), CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl.get(), CURLOPT_NOSIGNAL, 1);
int voice_upgrade_download_timeout = CFGI2(CONFIG_FILE_GLOBAL_CONFIG, "property_set", "default_voice_upgrade_download_timeout", 180);
curl_easy_setopt(curl.get(), CURLOPT_TIMEOUT, voice_upgrade_download_timeout);
std::exception_ptr exception;
try {
CURLcode res = curl_easy_perform(curl.get());
// 获取HTTP状态码
long httpCode = 0;
curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE , &httpCode);
if (res != 0 || httpCode != 200) {
FileUtils::RemoveFile(dest_file);
throw SysIOException("DownLoadAndCheck failed : " + std::to_string(res));
}
MD5 md5class;
char* md5_check = md5class.digestFile(dest_file.c_str());
LOGD("Download voice md5 is: %s", md5_check);
std::string src_md5 = md5;
std::transform(src_md5.begin(), src_md5.end(), src_md5.begin(), ::tolower);
if (memcmp(md5_check, src_md5.c_str(), 32) != 0) {
FileUtils::RemoveFile(dest_file);
throw SysIOException("MD5 Check failed");
}
LOGD("DownLoadAndCheck md5 success");
// 语音包下载成功,开始应用语音包
if (!id.empty()) {
if (this->SaveAndApplyVoicePackage(id) == 0) {
LOGD("SaveAndApplyVoicePackage success.");
StdIntMsgSharePtr msg = StdIntMsg::Create();
msg->val = 100;
AposSdk::Publish(TOPIC_SWEEP_VOICE_UPDATE_STATUS, msg);
} else {
LOGD("SaveAndApplyVoicePackage failed.");
StdIntMsgSharePtr msg = StdIntMsg::Create();
msg->val = -1;
AposSdk::Publish(TOPIC_SWEEP_VOICE_UPDATE_STATUS, msg);
}
}
} catch (...) {
exception = std::current_exception();
}
if (exception) {
std::rethrow_exception(exception);
}
}
原文地址: https://www.cveoy.top/t/topic/nENd 著作权归作者所有。请勿转载和采集!